Bash: Command Line Arguments to Bash Script Examples


Let's say you have a bash script with name script.sh with a simple hello message.

sample.sh
#!/bin/bash

echo "hello!"

Now if you want to have this script accept command line string arguments, you can simply add it when you run your script.

# ./script.sh Sam

You will see this prints out only "hello!" because we have not made use of the argument passed in the script, so lets modify it.

#!/bin/bash

echo "hello $1!"

Now lets run the script again by passing our 1st argument.

# ./script.sh Sam

hello Sam!

There we have it!

If you add more arguments to the bash script when executing you can access them using $2, $3, $4... and so on!

If you want to fetch the name of the script you can make use of $0

Example:
#!/bin/bash

echo "hello $1! you just executed the script: $0!"

hello Sam! you just executed the script: script.sh

Pass Arguments to bash script command line example

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap