0

I am new to bash scripting and struggle to update a parameter with a default value. I observe some of my optional parameters are not getting updated according to the user input.

Below is the interesting part of my bash script. For instance, I set the variable REGISTRATION to 1, then the user can chose to set it to 0 instead.

# default values
DIM=3
BIASFIELDCORRECTION=1
SKULLSTRIPPING=0
REGISTRATION=1
RESAMPLRES=0

# reading command line arguments
while getopts ":s:d:b:res:reg:h:" OPT
  do
  case $OPT in
      h) #help
   Help
   exit 0
   ;;
      d)  # dimension
   DIM=$OPTARG
   ;;
      b)  # bias field correction
   BIASFIELDCORRECTION=$OPTARG
   ;;
      s)  # skull stripping
   SKULLSTRIPPING=$OPTARG
   ;;
      res)  # resampling resolution
   RESAMPLRES=$OPTARG
   ;;
      reg)  # resampling resolution
   REGISTRATION=$OPTARG
   ;;
     \?) # getopts issues an error message
   exit 1
   ;;
  esac
done

echo "Registration:" $REGISTRATION

The problem is that the last line always outputs Registration: 1, even when the user set the variable to 0 with the following syntax:

bash preprocessingPipeline.sh -reg 0

I checked all my parameters and it appears that only res, reg and s present this problem. d and b are correctly updated. Can someone tell my what's wrong with my approach?

Barbara Gendron
  • 385
  • 1
  • 2
  • 16
  • Not asserting that this is your immediate problem, but all-caps variable names are in a space used by the system (for names that either reflect or modify behavior of the shell and other standardized tools), whereas names with at least one lower-case variable are guaranteed not to have meaning to the shell or other POSIX-specified tools. Sticking to lower-case names thus ensures you won't be conflicting with a new reserved name the shell adds in the future, and avoids common mistakes like `for PATH in */; do ...` preventing a script from being able to start further external commands. – Charles Duffy Feb 15 '23 at 16:39
  • 3
    The bigger issue is re: `res` and `reg` being _sequences of characters_, but getopts expects only single-character flags. Consider tossing out getopts and instead following the practice described in [BashFAQ #35](https://mywiki.wooledge.org/BashFAQ/035). – Charles Duffy Feb 15 '23 at 16:41
  • 1
    `getopts` only processes 1-character options. `reg:` in the option string means there are options `-r`, `-e`, and `-g`. and `-g` takes an argument. – Barmar Feb 15 '23 at 16:42
  • Thanks a lot, I couldn't find that the number of characters was the core of the problem. Sorry for the duplicate then. – Barbara Gendron Feb 15 '23 at 16:47

0 Answers0