Skip to content
Home » Bash Arguments: A Quick and Dirty Guide

Bash Arguments: A Quick and Dirty Guide

Have you ever found yourself typing the same commands over and over again in your terminal, wishing there was a quicker way to execute them? Or perhaps you’ve come across a script that looks useful, but it requires you to pass in some arguments and you’re not sure how to do that? If so, then learning about arguments in bash is for you!

What are Bash Arguments?

Bash arguments are pieces of information that you can pass to a script or command to modify its behavior. They are denoted by a $ followed by a number, starting with $0 for the name of the script itself, and $1, $2, $3, etc. for the arguments passed in.

For example, let’s say you have a script called greet.sh that prints a personalized greeting. Without arguments, it might look like this:

# greet.sh
echo "Hello, world!"

But with arguments, you could use it like this:

./greet.sh "John Doe"

This would output "Hello, John Doe!".

You can also use arguments within the script itself by accessing them through the $1, $2, etc. variables. For example:

# greet.sh
echo "Hello, $1!"

Surprising Fact

Did you know that you can use arguments in bash not only with scripts, but with regular commands as well? For example, the grep command is used to search for patterns in text files, but you can also pass in arguments to modify its behavior. For example:

grep -r "itvraag.nl" .

This would search for the string "itvraag.nl" recursively (-r flag) in the current directory (.).

5 Tips for Using Bash Arguments

  1. Use -help or h to display a command’s usage and available options. For example: grep --help
  2. Use man to view a command’s man page, which provides detailed information about its usage and options. For example: man grep
  3. Use quotes ('' or "") to pass in arguments with spaces. For example: ./greet.sh "John Doe"
  4. Use $@ to access all arguments as an array. For example: echo $@
  5. Use $# to access the number of arguments passed in. For example: if [ $# -eq 0 ]; then echo "No arguments passed in."; fi

Additional Resources

Challenge

Try creating a script that calculates the average of a list of numbers passed in as arguments. Use the bc command to perform the calculations. For example:

# avg.sh
sum=0
for num in "$@"
do
  sum=$(echo "$sum + $num" | bc)
done
echo "The average is: $(echo "$sum / $#" | bc)"

To test it out, you can run it like this:

./avg.sh 10 20 30 40 50

This should output "The average is: 30".

Leave a Reply

Your email address will not be published. Required fields are marked *

12 + 2 =