Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 检查是否缺少特定参数-顺序不重要_Bash - Fatal编程技术网

Bash 检查是否缺少特定参数-顺序不重要

Bash 检查是否缺少特定参数-顺序不重要,bash,Bash,不考虑参数顺序,检查bash脚本中是否缺少特定参数的最简单方法(可能是一行程序)是什么 我想在脚本的开头指定一个名为REAL\u RUN的“布尔”变量,该变量基于所有脚本参数中是否包含参数--dry RUN而具有true或false。大概是这样的: REAL_RUN=... # <-- what to put here ? if [ "$REAL_RUN" = true ] ; then # do something fi 相反,对于以下示例,必须将REAL\u RUN设置为fal

不考虑参数顺序,检查bash脚本中是否缺少特定参数的最简单方法(可能是一行程序)是什么

我想在脚本的开头指定一个名为
REAL\u RUN
的“布尔”变量,该变量基于所有脚本参数中是否包含参数
--dry RUN
而具有
true
false
。大概是这样的:

REAL_RUN=... # <-- what to put here ?
if [ "$REAL_RUN" = true ] ; then
   # do something
fi
相反,对于以下示例,必须将
REAL\u RUN
设置为
false

./run.sh --dry-run
./run.sh foo --dry-run
./run.sh --dry-run bar
./run.sh foo --dry-run bar

您可以创建如下函数:

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"

问候

您可以在
BASH
中使用此正则表达式匹配:

[[ $# -eq 0 || ! $* =~ (^| )--dry-run( |$) ]] &&
REAL_RUN=true || REAL_RUN=false;

echo "REAL_RUN=$REAL_RUN"

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
有些人喜欢放特殊的标记
单独一行,但在这样一个简单的
情况下
,这似乎太过分了

这有点不准确,因为它无法区分参数之间的空格和引用的空格。有人可以编写
命令--dry run“
,它会触发条件,即使严格来说,这应该被解释为一个静态字符串参数,以文本空间开始和结束,而不是一个选项。(为了防止出现这种情况,可能需要循环使用
“$@”
并检查文本参数:

REAL_RUN=true
for arg; do    # shorthand for 'for arg in "$@"; do'
    case $arg in
      --dry-run) REAL_RUN=false;;
    esac
done

但是这肯定不再是一行。)

命令替换捕获函数的标准输出,而不是其返回代码(您应该避免过时的backticks语法)。正确的使用方法要简单得多:
包含“apple”$@“&&echo”存在“| | echo”不存在”
@tripleee一个问题,为什么反勾号的使用过时了?我总是理解回跳,就像在同一个进程中发生的替换,而$()分叉进入一个新进程。是这样吗?不,它们基本上是等价的,尽管它们解析的一些细节不同。见@tripleee ok。现在明白了。谢谢
REAL_RUN=true
for arg; do    # shorthand for 'for arg in "$@"; do'
    case $arg in
      --dry-run) REAL_RUN=false;;
    esac
done