Bash Script Arguments
What are Arguments?
Arguments are values you give to a script when you run it, written after the script name.
Inside the script, you read them with special variables: $1 is the first argument, $2 the second, and so on.
Read Arguments
Example: Use Two Arguments
Save this as greet.sh:
#!/bin/bash
echo "Hello, $1!"
echo "Today is $2."
Run it:
./greet.sh Liam Monday
Hello, Liam!
Today is Monday.
Wrap an argument in quotes if it contains spaces: ./greet.sh "Liam Smith" Monday.
Special Variables
$0: The name of the script$1,$2...: The first, second ... argument$#: The number of arguments$@: All the arguments, as separate words
Example: Show the Special Variables
Save this as info.sh:
#!/bin/bash
echo "Script: $0"
echo "Number of arguments: $#"
echo "All arguments: $@"
Run it:
./info.sh red green blue
Script: ./info.sh
Number of arguments: 3
All arguments: red green blue
Loop Through All Arguments
Use "$@" in a for loop to handle every argument. Keep the quotes, so arguments with spaces stay together:
Example: Loop Through Arguments
Save this as list.sh:
#!/bin/bash
for item in "$@"; do
echo "Item: $item"
done
Run it:
./list.sh apple banana cherry
Item: apple
Item: banana
Item: cherry
Check the Number of Arguments
Use $# to make sure the user gave enough arguments, and show how to use the script if not:
Example: Require an Argument
Save this as hello.sh:
#!/bin/bash
if [ $# -lt 1 ]; then
echo "Usage: $0 name"
exit 1
fi
echo "Hello, $1!"
Run it:
./hello.sh
Usage: ./hello.sh name
Default Values
Use ${1:-default} to use a default value when an argument is missing:
Example: Use a Default Value
Save this as welcome.sh:
#!/bin/bash
name=${1:-World}
echo "Hello, $name!"
Run it:
./welcome.sh
Hello, World!
Shift Arguments
The shift command removes the first argument, so $2 becomes $1, and so on:
Example: Use shift
Save this as first.sh:
#!/bin/bash
echo "First: $1"
shift
echo "Now first: $1"
echo "Left: $#"
Run it:
./first.sh one two three
First: one
Now first: two
Left: 2