0

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.

DevanDev
  • 161
  • 1
  • 2
  • 17
  • 1
    You're not assigning anything to variables U and W, what were you expecting? – oguz ismail Sep 03 '19 at 18:48
  • I am assigning -U Markus -W Workflow_000000000000334 two values to parameters -U and -W, is it a wrong way to assign the variables ? – DevanDev Sep 03 '19 at 21:18
  • You assign `argument="$OPTARG"` and `String="$OPTARG"`. You assign variables named `argument` and `String`, not `U` or `W`. – KamilCuk Sep 03 '19 at 21:24
  • @KamilCuk Yes, now i have altered my script,but still the file dummy_t1t2.nii.gz that i have passed to the variable -T is not recognized – DevanDev Sep 03 '19 at 21:37
  • 1
    `":TDNUW"` - none of the options you specified take any arguments. `getopts` needs to know which options take argument, which doesn't – KamilCuk Sep 03 '19 at 21:48
  • @KamilCuk , all options take arguments and the arguments are provided through command line – DevanDev Sep 03 '19 at 21:55
  • 1
    But `optarg` doesn't now about that. From [man optarg](http://man7.org/linux/man-pages/man1/getopts.1p.html) : `If a character is followed by a , the option shall be expected to have an argument` if it isn't, then it isn't. – KamilCuk Sep 03 '19 at 21:57
  • 1
    @KamilCuk , so should i use the colon after the options ?. – DevanDev Sep 03 '19 at 22:40

1 Answers1

2

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))
KamilCuk
  • 120,984
  • 8
  • 59
  • 111