my requirement is really simple, I just want to check that if the getopts
argument is empty or not. I am kicking my script using the jenkins and need to check that if the provided value is empty then set the default otherwise use the provided value:
and passing the arguments to the shell script like this:
./rds-db-dump.sh -s ${source_instance_id} -c ${target_instance_class} -i ${source_snapshot_id}
snippet from shell script:
while getopts ":s:c:i:h" opt; do
case ${opt} in
s) SOURCE_INSTANCE_ID="${OPTARG}"
;;
c) TARGET_INSTANCE_CLASS="${OPTARG}"
;;
i) SOURCE_SNAPSHOT_ID="${OPTARG}"
;;
h) usage && exit 1
;;
\?) echo "Invalid option -${OPTARG}" >&2
usage && exit 1
;;
esac
done
echo "SOURCE_SNAPSHOT_ID: ${SOURCE_SNAPSHOT_ID}"
echo "TARGET_INSTANCE_CLASS: ${TARGET_INSTANCE_CLASS}"
when I kicked off this job, it doesn't give me desired result:
How I can achieve that with getopts
to check if the argument is empty than assign some default value of perform some operation otherwise use the provided value of argument.
It's not really within getopts, but you can have your shell expand the variable differently if it is empty or not eg
i) SOURCE_SNAPSHOT_ID="${OPTARG:-yourdefaultvalue}"
Alternatively you can just check if OPTARG is empty and continue, or set default values after the whole loop eg either of these would set SOURCE_SNAPSHOT_ID if and only if it was empty before
: ${SOURCE_SNAPSHOT_ID:=yourdefaultvalue}
SOURCE_SNAPSHOT_ID=${SOURCE_SNAPSHOT_ID:-yourdefaultvalue}
See the "Parameter Expansion" of the bash manual for more information on such variable usage (only quoting the two I used):
${parameter:-word}
Use Default Values. If parameter is unset or null, the expansion of word is substituted.
Otherwise, the value of parameter is substituted.
${parameter:=word}
Assign Default Values. If parameter is unset or null, the expansion of word is assigned to
parameter. The value of parameter is then substituted. Positional parameters and special
parameters may not be assigned to in this way.
just test it:
Z) testarg=$OPTARG
;;
if [ -z "$testarg" ]; then $(set default value); fi
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.