Script Arguments
Scripts receive arguments as $1, $2, and so on, letting you pass in values.
Syntax
$1 $2 ... # positional arguments
$# # argument count
$@ # all argumentsValues passed to a script on the command line are available as numbered variables.
The special variables
$1,$2,$3— the first, second, third argument.$0— the name of the script itself.$#— how many arguments were given.$@— all the arguments as a list.
This is what makes a script reusable: ./greet.sh Alice and ./greet.sh Bob behave differently based on $1.
Example
#!/bin/bash
# greet.sh - say hello to someone
echo "Script name: $0"
echo "You gave $# argument(s)"
echo "Hello, $1!"
# Run it like this:
# ./greet.sh Alice
# Output:
# Hello, Alice!When to use it
- A backup script accepts the target directory as '$1' so operators can call './backup.sh /var/data' without editing the script.
- A deployment script uses '$@' to forward all its arguments to an inner command, preserving quoting and spaces.
- A script validates argument count with 'if [ $# -lt 2 ]' and prints usage instructions when called incorrectly.
More examples
Access positional arguments
Shows the positional parameter variables $0, $1, $2 and a sample invocation to make them concrete.
#!/bin/bash
# $0 = script name, $1 = first arg, $2 = second arg
echo "Script: $0"
echo "Target host: $1"
echo "Deploy path: $2"
# Example call: ./deploy.sh server.example.com /opt/appValidate argument count
Checks $# (argument count) and exits with a usage message if the minimum required arguments are not provided.
#!/bin/bash
if [ $# -lt 2 ]; then
echo "Usage: $0 <host> <path>" >&2
exit 1
fi
HOST=$1
PATH_ARG=$2
echo "Deploying to $HOST:$PATH_ARG"Loop over all arguments
Uses "$@" to iterate over every argument, making a script that operates on multiple targets scalable.
#!/bin/bash
# $@ expands to all arguments, preserving quoting
for server in "$@"; do
echo "Restarting nginx on: $server"
ssh "$server" 'sudo systemctl restart nginx'
done
# Call: ./restart_nginx.sh web1 web2 web3
Discussion