Shell Scripting – How to Pass Named Arguments to Shell Scripts

argumentsbashshell-scriptzsh

Is there any easy way to pass (receive) named parameters to a shell script?

For example,

my_script -p_out '/some/path' -arg_1 '5'

And inside my_script.sh receive them as:

# I believe this notation does not work, but is there anything close to it?
p_out=$ARGUMENTS['p_out']
arg1=$ARGUMENTS['arg_1']

printf "The Argument p_out is %s" "$p_out"
printf "The Argument arg_1 is %s" "$arg1"

Is this possible in Bash or Zsh?

Best Answer

If you don't mind being limited to single-letter argument names i.e. my_script -p '/some/path' -a5, then in bash you could use the built-in getopts, e.g.

#!/bin/bash

while getopts ":a:p:" opt; do
  case $opt in
    a) arg_1="$OPTARG"
    ;;
    p) p_out="$OPTARG"
    ;;
    \?) echo "Invalid option -$OPTARG" >&2
    ;;
  esac
done

printf "Argument p_out is %s\n" "$p_out"
printf "Argument arg_1 is %s\n" "$arg_1"

Then you can do

$ ./my_script -p '/some/path' -a5
Argument p_out is /some/path
Argument arg_1 is 5

There is a helpful Small getopts tutorial or you can type help getopts at the shell prompt.

Related Question