How to conditionally add flags to shell scripts?

拜拜、爱过 提交于 2020-01-13 09:34:36

问题


I want to run a command inside my bash script with or without a -v flag depending on if the environment variable $VERBOSE is defined. Something like this:

#!/bin/bash

/usr/local/bin/mongo-connector \
  -m $MONGO_HOST \
  -t $NEO_URI \
  [if $VERBOSE then -v ] \
  -stdout

回答1:


#!/bin/bash

/usr/local/bin/mongo-connector \
  -m $MONGO_HOST \
  -t $NEO_URI \
  ${VERBOSE:+-v} \
  -stdout

If VERBOSE is set and non-empty, then ${VERBOSE:+-v} evaluates to -v. If VERBOSE is unset or empty, it evaluates to the empty string. Note that this is an instance where you must avoid using double quotes. If you write: cmd "${VERBOSE:+-v}" rather than cmd ${VERBOSE+:v}, the behavior is semantically different when VERBOSE is empty or unset. In the former case, cmd is called with one argument (the empty string), while in the latter case cmd is called with zero arguments.

To test if VERBOSE is set to a particular string, you can do things like:

/usr/local/bin/mongo-connector \
  -m $MONGO_HOST \
  -t $NEO_URI \
  $(case ${VERBOSE} in (v1) echo foo;; (v2) echo bar;; (*) echo default; esac )\
  -stdout



回答2:


For readability, consider using an array to store the arguments.

args=(
  -m "$MONGO_HOST"
  -t "$NEO_URI"
  -stdout
)
if [[ -v VERBOSE ]]; then
    args+=(-v)
fi
/usr/local/bin/mongo-connector "${args[@]}"


来源:https://stackoverflow.com/questions/42985611/how-to-conditionally-add-flags-to-shell-scripts

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!