在不考虑参数顺序的情况下,检查bash脚本中是否缺少特定参数的最简单(也可能是一行)方法是什么?
我想在脚本的开头分配一个名为REAL_RUN的“布尔”变量,并根据所有脚本参数中包含的参数--dry-run的存在与否,使用true或false。如下所示:
REAL_RUN=... # <-- what to put here ?
if [ "$REAL_RUN" = true ] ; then
# do something
fi我希望REAL_RUN在以下情况下被分配true:
./run.sh
./run.sh foo bar
./run.sh foo --dry-run-with-unexpected-suffix bar
./run.sh foo ------dry-run bar相反,对于以下示例,必须将REAL_RUN设置为false
./run.sh --dry-run
./run.sh foo --dry-run
./run.sh --dry-run bar
./run.sh foo --dry-run bar发布于 2018-06-12 12:24:53
case是可移植到POSIX sh的。它可以是一行代码,尽管按照惯例,该语句被分成多个物理行。
case " $@ " in *\ --dry-run\ *) REAL_RUN=false;; *) REAL_RUN=true;; esac或者为了易读性
# Put spaces around "$@" to make the later logic simpler
case " $@ " in
# If --dry run exists with spaces on both sides,
*\ --dry-run\ *)
# Set REAL_RUN to false
REAL_RUN=false;;
# Otherwise,
*)
# ... it's true.
REAL_RUN=true;;
esac有些人喜欢将特殊的令牌;;放在一行中,但是在这样一个简单的case中,这似乎有点过分。
这有点不精确,因为它无法区分参数和引号之间的空格。有人可以编写command " --dry-run ",它会触发条件,即使严格地说,这应该被解释为以文字空格开始和结束的静态字符串参数,而不是一个选项。(为了防止这种情况,可能会在"$@"上循环并检查文字参数:
REAL_RUN=true
for arg; do # shorthand for 'for arg in "$@"; do'
case $arg in
--dry-run) REAL_RUN=false;;
esac
done但这绝对不再是一句话了。)
发布于 2018-06-11 22:43:32
您可以在BASH中使用此正则表达式匹配
[[ $# -eq 0 || ! $* =~ (^| )--dry-run( |$) ]] &&
REAL_RUN=true || REAL_RUN=false;
echo "REAL_RUN=$REAL_RUN"发布于 2018-06-11 22:29:38
您可以创建如下所示的函数:
contains () {
local e match="$1"
shift
for e; do [[ "$e" == "$match" ]] && return 0 ; done
return 1
}然后通过传递已经来自系统的数组来使用它:
[[ `contains "apple" "$@"` -eq 0 ]] && echo "Is present" || echo "Is not present"致以问候!
https://stackoverflow.com/questions/50799794
复制相似问题