At first glance, the trivial task appeared: to write a script with various options at startup. Suppose you need to handle only two options: name and dir. And the task is really trivial, provided that our options are short. But if there is a burning desire to use long options, then write it is gone: getopts, which was planned to be used initially, is not suitable for bash at all.#!/bin/ksh while getopts "f(file):s(server):" flag do echo "$flag" $OPTIND $OPTARG done #!/bin/bash while true; do case "$1" in -n | --name ) echo NAME="$2"; shift 2;; -d | --dir ) echo DIR="$2"; shift 2;; esac done #!/bin/bash while getopts ":n:d:-:" OPTION; do case "$OPTION" in -) case "$OPTARG" in name) echo LONG_NAME="${!OPTIND}";; dir) echo LONG_DIR="${!OPTIND}" ;; esac;; n) echo SHORT_NAME="$OPTARG" ;; d) echo SHORT_DIR="$OPTARG" ;; esac done #!/bin/bash . getopts_long while getopts_long :d:n::vh opt \ name required_argument \ dir required_argument \ help 0 "" "$@" do case "$opt" in n|name) echo NAME="$OPTLARG";; d|dir) echo DIR="$OPTLARG";; help 0 "" "$@" esac done #!/bin/bash . ./shflags DEFINE_string 'name' 'world' 'comment for name' 'n' DEFINE_string 'dir' 'dir' 'comment for dir' 'd' FLAGS "$@" || exit 1 eval set -- "${FLAGS_ARGV}" echo "Name is ${FLAGS_name} and dir is ${FLAGS_dir}" Source: https://habr.com/ru/post/133860/
All Articles