Blog Archive

Tuesday, November 13, 2018

Passing named arguments to shell scripts

https://unix.stackexchange.com/questions/129391/passing-named-arguments-to-shell-scripts

Label:  single-letter argument names

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.

No comments:

Post a Comment