How to read shell script command line arguments

Unix/Linux shell script args FAQ: How do I access Unix or Linux shell script command line arguments?

If you want to process command line options or flags ("-a", "-b", etc.), you should use the Unix/Linux getopts shell function to process those command line options, as shown here:

while getopts :hj:ln:s: option
do
    case "$option" in
    h)
         DO_HELP=1
         ;;
    j)
         searchFor=$OPTARG
         DO_JUMP=1
         ;;
    l)
         DO_LIST=1
         ;;
    n)
         searchFor=$OPTARG
         DO_NUMBER=1
         ;;
    s)
        searchFor=$OPTARG
        DO_SEARCH=1
        ;;
    *)
        echo "Hmm, an invalid option was received. -j, -n, and -s require an argument."
        echo "Here's the usage statement:"
        echo ""
        displayTpUsageStatement
        return
        ;;
        esac
done

I don't have time to get into it all today, but to explain this quickly:

  • The shell script I took this from allows the following command line flags/options:
    • -h
    • -j
    • -l
    • -n
    • -s
  • The flags/options -j, -n, and -s allow a parameter to be passed after the flag, like "-n 234", or "-s SearchString". That's why you need the ":" characters in the "while getopts" statement, and why the lines in the case statement refer to $OPTARG.

For all the source code related to this getopts/OPTARG shell script example, see the source code for my Teleport command.

Handling shell script command-line arguments

In another situation, if you're just expecting one or two parameters to be passed into a Unix or Linux shell script, and these parameters aren't options/flags to your script (like "-a" or "-f"), you can access the shell script arguments through variables named $1, $2, etc.

Here's a short example where I'm expecting two shell script command line arguments. If either of these command line arguments is blank, I display a usage statement and exit my script:

if [ -z "$1" ] || [ -z "$2" ]
then
  echo "Usage: mmv oldExtension newExtension"
  exit -1
fi

In the case of this shell script, I expect it to be executed like this:

mmv.sh JPG jpg

so $1 in my script will be "JPG", and $2 will be "jpg".

If it helps to see more of this script, I took that example shell script code from my "How to rename many files at once Unix shell script".

Unix and Linux shell script command line arguments (args)

Again, there is much more to say about shell script command line flags (options), but I hope this Linux/Unix/getopts/OPTARG shell script example will point you in the right direction.

And once again, if you're just looking to process simple Unix shell script arguments, you can use the shell script example shown earlier.

Post new comment

The content of this field is kept private and will not be shown publicly.