dell xps
dell xps

Reputation: 51

How to use getopt long option in bash script

I want to write one script something like below with the long option to be provided by user in cmd line argument.

example:

./script.sh --user username --branch branchname --start_time yyy-mm-dd

If possible ignore the order. Not sure if we can apply the logic to ignore the order. Also, force user to provide the value otherwise throw error message that missing value.

Pasting code block

script_name=$(basename "$0")
short=u:c:e:p:b:t:n:
long=user:,component:,engagement:,product:,branch:,tag:,name:,help

TEMP=$(getopt -o $short --long $long --name "$script_name" -- "$@")

eval set -- "${TEMP}"
while :; do
    case "${1}" in
        -u | --user         ) user="$2";            shift 2 ;;
        -c | --component    ) comp="$2"; COMP=$(echo $comp | tr [:upper:] [:lower:]) ;               shift 2 ;;
        -e | --engagement   ) eng="$2"; ENG=$(echo $eng | tr [:lower:] [:upper:]) ;                  shift 2 ;;
        -p | --product      ) product="$2"; PRODUCT=$(echo $product | tr [:lower:] [:upper:]) ;      shift 2 ;;
        -b | --branch       ) branch="$2";          shift 2 ;;
        -t | --tag          ) tag="$2";             shift 2 ;;
        -n | --name         ) name="$2";            shift 2 ;;
        --help              ) usage;                exit 0 ;;
        --                  ) shift;               break  ;;
        *                   ) echo "invalid option"; exit 1 ;;
    esac
done

Upvotes: 1

Views: 4858

Answers (1)

Kaffe Myers
Kaffe Myers

Reputation: 464

script_name=$(basename "$0")
short=u:b:s:
long=user:,branch:,start_time:,help

read -r -d '' usage <<EOF
Manually written help section here
EOF

TEMP=$(getopt -o $short --long $long --name "$script_name" -- "$@")

eval set -- "${TEMP}"

while :; do
    case "${1}" in
        -u | --user       ) user=$2;             shift 2 ;;
        -b | --branch     ) branch=$2;           shift 2 ;;
        -s | --start_time ) start_time=$2;       shift 2 ;;
        --help            ) echo "${usage}" 1>&2;   exit ;;
        --                ) shift;                 break ;;
        *                 ) echo "Error parsing"; exit 1 ;;
    esac
done

Set your short and long options. A colon implies it needs an option argument. Short options are written with no delimiter, long options are comma delimited.

The getopt command makes sure items come in an easily parsable order. In this example, we use a case statement to parse each option. All options are parsed first and then removed from $@.

What's left are the passed arguments that is not part of any defined option.

Upvotes: 2

Related Questions