How to read command line parameters in BASH Scripts

- by

Shell Scripts (BASH Scripts) can access command line parameters using the the variables $1, $2, $2 and so forth, up to $9. In fact, more parameters can be accessed by using curly brackets, like ${10}, ${187} and so forth.

Here’s an example:

#!/bin/bash

if [[ $1 == "x" ]]; then
  echo "Statement is true"
else
  echo "Statement is false"
fi

If we run the script with like this

script.sh x

it will tell us the statement is true. Otherwise, it’ll tell us the opposite.

Note the whitespace around the evaluation: [[ ]] is actually a command (much like the == operator) and therefore needs to be surrounded with whitespace.

Add your voice!

This site uses Akismet to reduce spam. Learn how your comment data is processed.