How to read command line parameters in BASH Scripts

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.





Jay is founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or drawing on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.

You can leave a comment on my original post.