繁体   English   中英

shell脚本的变量参数

[英]Variable arguments to a shell script

我想让我的脚本接受变量参数。 我如何单独检查它们?

例如

./myscript arg1 arg2 arg3 arg4

 or 

./myscript arg4 arg2 arg3

参数可以是任何数字,也可以是任何顺序。 我想检查是否存在arg4字符串,而不管参数号是什么。

我怎么做?

谢谢,

最安全的方法 - 处理参数中空白的所有可能性的方式,等等 - 是编写一个显式循环:

arg4_is_an_argument=''
for arg in "$@" ; do
    if [[ "$arg" = 'arg4' ]] ; then
        arg4_is_an_argument=1
    fi
done
if [[ "$arg4_is_an_argument" ]] ; then
    : the argument was present
else
    : the argument was not present
fi

如果你确定你的论点不会包含空格 - 或者至少,如果你并不特别担心这种情况 - 那么你可以将其缩短为:

if [[ " $* " == *' arg4 '* ]] ; fi
    : the argument was almost certainly present
else
    : the argument was not present
fi

这通过命令行“参数”的典型解释来快速松散地播放,但是我使用以下内容启动了大部分bash脚本,作为添加--help支持的简单方法:

if [[ "$@" =~ --help ]]; then
  echo 'So, lemme tell you how to work this here script...'
  exit
fi

主要的缺点是,这也会被request--help.logrequest--help.log --no--help等参数触发(不仅仅是--help ,这可能是你的解决方案的要求)。

要在您的案例中应用此方法,您可以编写如下内容:

[[ "$@" =~ arg4 ]] && echo "Ahoy, arg4 sighted!"

奖金! 如果您的脚本至少需要一个命令行参数,那么在没有提供参数时,您可以类似地触发帮助消息:

if [[ "${@---help}" =~ --help ]]; then
  echo 'Ok first yer gonna need to find a file...'
  exit 1
fi

如果绝对没有给出参数,它使用空变量替换语法${VAR-default}来产生--help参数。

也许这可以帮助。

#!/bin/bash
# this is myscript.sh

[ `echo $* | grep arg4` ] && echo true || echo false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM