Sample Header Ad - 728x90

passing long positional arguments in bash script

0 votes
2 answers
114 views
I would like to pass long arguments to script, and referred this link . I created this my_script:
#!/usr/bin/env bash
#
# Adapted from https://www.shellscript.sh/examples/getopt/ 
#
set -euo pipefail

user_type=unset
user_id=unset
country=unset
dev_env=unset
position_id=unset

usage(){
>&2 cat &2 echo [$@] passed to script

args=$(getopt -a -o ha:b:c:d: --long help,user_type:,user_id:,country:,dev_env:,position_id: -- "$@")
if [[ $? -gt 0 ]]; then
  usage
fi

>&2 echo getopt creates [${args}]

eval set -- ${args}
while :
do
  case $1 in
    -a | --user_type)   user_type=$2    ; shift 2  ;;
    -b | --user_id)    user_id=$2     ; shift 2  ;;
    -h | --help)    usage      ; shift   ;;
    -c | --country)   country=$2   ; shift 2 ;;
    -d | --dev_env)   dev_env=$2   ; shift 2 ;;
    -e | --position_id) position_id=$2 ; shift 2 ;;
    # -- means the end of the arguments; drop this, and break out of the while loop
    --) shift; break ;;
    *) >&2 echo Unsupported option: $1
       usage ;;
  esac
done

if [[ $# -eq 0 ]]; then
  usage
fi

>&2 echo "user_type   : ${user_type}"
>&2 echo "user_id    : ${user_id} "
>&2 echo "country   : ${country}"
>&2 echo "dev_env   : ${dev_env}"
>&2 echo "position_id   : ${position_id}"
>&2 echo "$# parameter/s remaining: $@"
>&2 echo "Looping through remaining parameter/s:"
# set input field separator to keep quoted parameters together
# for example, "my input" will remain as one input
IFS=$'\n'
for param in $@; do
   >&2 echo -e "\t${param}"
done

echo "user ${user_type} with user id ${user_id} has been created with position_id $position_id"
exit 0
and on terminal tried running it as:
bash test_bash --user_type abc --user_id a1b2 --country aud --dev_env uat --position_id aFWf
I am getting just help message like:
[--user_type abc --user_id a1b2 --country aud --dev_env uat --position_id aFWf] passed to script
getopt creates [ --user_type 'abc' --user_id 'a1b2' --country 'aus' --dev_env 'uat' --position_id 'aFWf' --]
Usage: test_bash]
   [ -a | --user_type input
   [ -b | --user_id input ]
   [ -c | --country input ] 
   [ -d | --dev_env input ]
   [ -e | --position_id input ]
I have tried to update/change few things like args=getopt with couple of other options. but I args are not been parsed by script. Appriciate your help in advance. Thanks.
Asked by SheCodes (103 rep)
Mar 24, 2025, 06:47 AM
Last activity: Mar 25, 2025, 11:17 AM