Search code examples
bashshellgetopts

Problem in passing command line arguments using getopts


I am trying to pass commandline arguments to my workflow script using getopts but the code throws an error

Following is the snippet of code for passing command line arguments

# take strings as arguments.
while getopts "TDNUW:" opt; do
  case "$opt" in
     T) T="$OPTARG" ;;
     D) D="$OPTARG" ;;
     N) N="$OPTARG" ;;
     U) U="$OPTARG" ;;
     W) W="$OPTARG" ;;
     \?) echo "Usage:[-T T1wfilename] [-D Dfilename] [-N Stream_Number] [-U User] [-W Workflow]";;

    esac
  done 
 shift $(expr $OPTIND - 1)

#Subjects Directory with $U : UserId

SUBJECTS_DIR=/Bio/Bmax/data/imaging_data/$U

#Subjects path with $W : workflow number    

SUBJECT_PATH=$SUBJECTS_DIR/$W

I have tried calling the script using the options

./code.sh -T dummy_t1t2.nii.gz -D dummy_dti.nii.gz -N 100000 -U Markus -W Workflow_000000000000334

and i am encountering an error

Error: input image /Bio/Bmax/data/imaging_data/// not valid

The arguments that i have passed through commandline are not interpreted by the code, could some one please provide me some hint why my script could not recognize the arguments.


Solution

  • You need to assign the variables you want to use manually. getopts doesn't do the work for you.

    You need a : after each letter option to tell getopts it is a option that takes argument.

    while getopts "T:D:N:U:W:" opt; do
      case "$opt" in
         T) T="$OPTARG" ;;
         D) D="$OPTARG" ;;
         N) N="$OPTARG" ;;
         U) U="$OPTARG" ;;
         W) W="$OPTARG" ;;
         \?) echo "Usage:[-T T1wfilename] [-D Dfilename] [-N Stream_Number] [-U User] [-W Workflow]" ;;
        esac
     done 
     shift $((OPTIND - 1))