Cancel

Non-Positional/Positional arguments in Bash

Positional arguments are parameters that we can supply to our bash script while executing.

1
2
3
4
5
6
7
8
9
# don't forget to set execute permission.
cat <<EOF > my_script.sh
echo "Hi, \$1 \$2"
EOF

# first name and last name
./my_script.sh Yafiz Abraham
#
./my_script.sh Abraham Yafiz

Remember: You cannot change the position of your given arguments, because your variables will change their places too. If you do, then your last name will be the first argument, and your first name will be the last argument.

That is why we do have one more option call non-positional arguments.

In the real world, we use non-positional arguments most of them instead of positional parameters. here you can change the position of your arguments as well with no issue.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# don't forget to set execute permission.
cat <<EOF > my_script.sh
while [[ "$1" =~ ^- ]]; do
  case $1 in
    -v)
      echo "version: 1.2.0"
      exit
      ;;
    -f)
      shift; first_name=$1
      ;;
    -l)
      shift; last_name=$1
      ;;
    * | -h)
      echo "Usage: $0 [vhfl]"
      echo "Example: $0 [-f FIRST_NAME] [-l LAST_NAME]"
      exit
      ;;
  esac; shift
done
EOF

# set condition if you want at least one option required.
if [[ -z $first_name ]]; then
  echo "ERROR: first name is required!"
else
  echo "Hi, $first_name $last_name"
fi

# run with
./my_script.sh -v # program's version
./my_script.sh -h # get help

# run program with arguments
./my_script.sh -f Yafiz -l Abraham

# run program with arguments but change position.
# you can see, both values are in the same place.
# instead of the wrong place.
./my_script.sh -l Abraham -f Yafiz