2

I have a bash file where I am passing arguments like

bash foo.sh update -f /var/ -v true

so according to this answer my script should look like

if [[ "$1" == "update" ]]; then
    updater 
fi

function updater(){
    verbose='false'
    fflag=''
    error=''

while getopts 'f:v' flag; do
  case "${flag}" in 
    f) fflag="${OPTARG}";;
    v) verbose='false';;
    *) error="bflag";;
  esac
done

  echo $fflag
}

I am using the first script as an entry point, because I have other function that do other things, but for some reason the script above does not even show the value of the $fflag I tried moving out the getopts loop out of the function to no avail

Community
  • 1
  • 1
user7342807
  • 323
  • 6
  • 21

1 Answers1

6

There are 3 issues:

  1. Define a function first at the start and then call it in your script
  2. You need to pass command line to your function using "$@"
  3. Before passing command line arguments call shift to remove first argument

You can use this script:

updater() {
    verbose='false'
    fflag=''
    error=''

    while getopts 'f:v' flag; do
      case "$flag" in
        f) fflag="${OPTARG}";;
        v) verbose='false';;
        *) error="bflag";;
      esac
    done

    declare -p fflag
}

if [[ $1 == "update" ]]; then
    shift
    updater "$@"
fi
anubhava
  • 761,203
  • 64
  • 569
  • 643