Privacy Policy
© 2025 linux101.dev

Bash: Script Parameters

Script parameters, or positional parameters, allow you to pass information into a script from the command line. They are accessed using special variables like `$1`, `$2`, and so on.

Accessing Parameters

Script name and arguments

                
#!/bin/bash
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
            

The special variable `$0` is the script's name. `$1` will be replaced by the first argument, `$2` by the second, and so on.

Running the script

bash greet.sh John Doe

This command would output the script name, "John", and "Doe" respectively.

Accessing all parameters and count

 echo "All parameters: $@"
echo "Number of parameters: $#"

The special variable `$@` expands to a list of all positional parameters passed to the script, while `$#` holds the number of parameters.

Iterate parameters

                
for param in "$@"; do
  echo "Parameter: $param"
done
                

The special variable `$@` expands to a list of all positional parameters passed to the script, while `$#` holds the number of parameters.

Assigning script parameters to variables

                
MY_FIRST_VARIABLE="$1"
MY_SECOND_VARIABLE="${2:-default_value}"
                

Second line assigns $2 to MY_SECOND_VARIABLE, but if $2 is unset or null, it uses default_value instead.