Unix/Linux shell script args FAQ: How do I access Unix or Linux shell script command line arguments?
When using the Bourne shell (
sh) or Bash, you can process Unix shell script command line arguments in at least two ways:
I show both of these solutions below.
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:
For all the source code related to this getopts/OPTARG shell script example, see the source code for my Teleport command.
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".
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.