Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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 "Argument p_out is %s" "$p_out"
printf "Argument arg_1 is %s" "$arg_1"

Is this possible in Bash or Zsh?

share|improve this question
1  
have a look at docopt – it helps with named parameters and does input validation, too –  Beat May 14 at 21:55

3 Answers 3

up vote 6 down vote accepted

The probably closest syntax to that is:

p_out='/some/path' arg_1='5' my_script
share|improve this answer
2  
Related to this, if the -k option is set in the calling shell, then my_script p_out='/some/path' arg_1='5' has the same effect. (All arguments in the form of an assignment are added to the environment, not just those assignments preceding the command.) –  chepner May 14 at 22:55

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) p_out="$OPTARG"
    ;;
    p) arg_1="$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 5
Argument arg_1 is /some/path

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

share|improve this answer

With zsh, you'd use zparseopts:

#! /bin/zsh -
zmodload zsh/zutil
zparseopts -A ARGUMENTS -p_out: -arg_1:

p_out=$ARGUMENTS[--p_out]
arg1=$ARGUMENTS[--arg_1]

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

But you'd call the script with myscript --p_out foo.

Note that zparseopts doesn't support abbreviating long options or the --p_out=foo syntax like GNU getopt(3) does.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.