Shell Script Arguments
Script arguments are the words you type after a script's name. The script reads them through numbered variables, starting at $1.
Greet the first argument
$1 holds the first word after the name.
cat > greet.sh <<'EOF'
#!/bin/bash
echo "Hello, $1"
EOF
chmod +x greet.sh
./greet.sh AnaName and count
$0 is the name, and $# is the count.
cat > showargs.sh <<'EOF'
#!/bin/bash
echo "Script: $0"
echo "Arguments: $#"
EOF
chmod +x showargs.sh
./showargs.sh a bUse the first two arguments
$1 and $2 hold the first two words.
cat > pair.sh <<'EOF'
#!/bin/bash
echo "First: $1, second: $2"
EOF
chmod +x pair.sh
./pair.sh Ana BoUse all the arguments
$@ holds every argument, in order.
cat > all.sh <<'EOF'
#!/bin/bash
echo "All: $@"
EOF
chmod +x all.sh
./all.sh red green blueExample
cat > showfile.sh <<'EOF'
#!/bin/bash
echo "Showing file $1"
cat "$1"
echo "That was $# file"
EOF
chmod +x showfile.sh
./showfile.sh notes.txtKey points
- First argument: $1 holds the first word after the script's name.
- Second argument: $2 holds the second word after the script's name.
- Argument count: $# holds the number of arguments.
- All arguments: $@ holds every argument, in order.
- Script name: $0 holds the script's own name, as you typed it.
In this example, the script prints the file name from $1. Then it shows the file with cat. Then it prints the argument count from $#.
Note
Quote "$1" when an argument may hold spaces.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
You run ./greet.sh Ana Bo. What is $2?