Reputation: 304
I've a script that has both 2 optional and 1 required flag. I'm using getopts to get the parameters.
#!/usr/bin/env bash
dt=`date '+%Y-%m-%d'`
while getopts s:fd flag
do
case "${flag}" in
s) onhand_src=${OPTARG};;
f) download_ftr=${OPTARG:-false};;
d) run_dt=${OPTARG:-$dt};;
esac
done
echo $onhand_src
echo $download_ftr
echo $run_dt
where -s is a required flag and f and d are optional flags. download_ftr
should default to false if -f flag is not passed, and run_dt should default to dt if no -d flag is passed.
However when I dont pass -f and -d flag, download_ftr and run_dt variables are not set to anything. What's missing?
Upvotes: 0
Views: 494
Reputation: 780724
Your code only sets the default values if the option is supplied with no corresponding argument. But if the option isn't used at all, you never execute those cases at all.
So you need to initialize the default values before the loop.
download_ftr=false
run_dt=dt
while getopts s:fd flag
do
case "${flag}" in
s) onhand_src=${OPTARG};;
f) download_ftr=${OPTARG:-false};;
d) run_dt=${OPTARG:-dt};;
esac
done
Upvotes: 2