Shell script arguments non positional

Is there a way to pass non-positional arguments to a shell script? Does the value explicitly indicate a flag?

. myscript.sh value1 value2
. myscript.sh -val1=value1 -val2=value2
+3
source share
5 answers

You can use it getopts, but I don’t like it because it is difficult to use and does not support long option names (not the POSIX version).

I recommend not using environment variables. There is too much risk of name clashes. For example, if your script reacts differently depending on the value of the environment variable ARCH, and it runs another script that (without your knowledge) also reacts to the environment variable ARCH, then you probably have a hard time finding an error that only appears occasionally.

This is the template I am using:

#!/bin/sh

usage() {
    cat <<EOF
Usage: $0 [options] [--] [file...]

Arguments:

  -h, --help
    Display this usage message and exit.

  -f <val>, --foo <val>, --foo=<val>
    Documentation goes here.

  -b <val>, --bar <val>, --bar=<val>
    Documentation goes here.

  --
    Treat the remaining arguments as file names.  Useful if the first
    file name might begin with '-'.

  file...
    Optional list of file names.  If the first file name in the list
    begins with '-', it will be treated as an option unless it comes
    after the '--' option.
EOF
}

# handy logging and error handling functions
log() { printf '%s\n' "$*"; }
error() { log "ERROR: $*" >&2; }
fatal() { error "$*"; exit 1; }
usage_fatal() { error "$*"; usage >&2; exit 1; }

# parse options
foo="foo default value goes here"
bar="bar default value goes here"
while [ "$#" -gt 0 ]; do
    arg=$1
    case $1 in
        # convert "--opt=the value" to --opt "the value".
        # the quotes around the equals sign is to work around a
        # bug in emacs' syntax parsing
        --*'='*) shift; set -- "${arg%%=*}" "${arg#*=}" "$@"; continue;;
        -f|--foo) shift; foo=$1;;
        -b|--bar) shift; bar=$1;;
        -h|--help) usage; exit 0;;
        --) shift; break;;
        -*) usage_fatal "unknown option: '$1'";;
        *) break;; # reached the list of file names
    esac
    shift || usage_fatal "option '${arg}' requires a value"
done
# arguments are now the file names
+4

:

$ val1=value1 val2=value2 ./myscript.sh

csh, env, ​​.

+3
+2
source

Example:

#!/bin/bash
while getopts d:x arg
do
        case "$arg" in
                d) darg="$OPTARG";;
                x) xflag=1;;
                ?) echo >&2 "Usage: $0 [-x] [-d darg] files ..."; exit 1;;
        esac
done
shift $(( $OPTIND-1 ))

for file
do
        echo =$file=
done
+2
source

Script has the following arguments: - $ 0 - script name - $ 1, $ 2, $ 3 .... - received arguments $ * = all arguments, $ # = number of arguments

Link: http://famulatus.com/ks/os/solaris/item/203-arguments-in-sh-scripts.html

0
source

All Articles