evanjdooner
evanjdooner

Reputation: 904

How to detect if an argument was passed to the script?

I am a novice at shell scripting. I have written a script that takes zero or more options and an optional path parameter. I want to use the current directory if a path parameter is not set.

This is the argument parsing section of the script:

OPTIONS=$(getopt -o dhlv -l drop-databases,help,learner-portal,verifier-portal -- "$@")

if [ $? -ne 0 ]; then
  echo "getopt error"
  exit 1
fi

eval set -- $OPTIONS

while true; do 
  case "$1" in
    -d|--drop-databases)  RESETDB=1
                          ;;
    -h|--help)            echo "$usage"
                          exit
                          ;;
    -l|--learner-portal)  LERPOR=1
                          ;;
    -v|--verifier-portal) VERPOR=1
                          ;;
    --)                   shift
                          break;;
    *)                    echo -e "\e[31munknown option: $1\e[0m"
                          echo "$usage"
                          exit 1
                          ;;
  esac
  shift
done

# Set directory of module
if [[ -n $BASH_ARGV ]]
then
  MOD_DIR=$(readlink -f $BASH_ARGV)
fi

if [[ -n $MOD_DIR ]]
then
  cd $MOD_DIR
fi

The script works as intended when called without and arguments, or when called with both options and a path.

However, when I run the script and only specify options, I get an error from readlink like so

$ rebuild_module -dv
readlink: invalid option -- 'd'
Try 'readlink --help' for more information.

Obviously, it's parsing the options wrong, but I'm not sure how to detect that I haven't passed a path, and therefore avoid calling readlink. How can I go about correcting this behaviour?

Upvotes: 0

Views: 152

Answers (1)

l0b0
l0b0

Reputation: 58768

You can do [ $# -ne 0 ] instead of [[ -n $BASH_ARGV ]]. The former is affected by shift/set, but the latter isn't:

$ cat test.sh 
echo "$#"
echo "${BASH_ARGV[@]}"
echo "$@"    
eval set -- foo bar
shift
echo "$#"
echo "${BASH_ARGV[@]}"
echo "$@"
$ bash test.sh x y z
3
z y x
x y z
1
z y x
bar

Upvotes: 1

Related Questions