如何处理 shell 脚本的变量参数?

问题描述 投票:0回答:3

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

例如

./myscript arg1 arg2 arg3 arg4

 or 

./myscript arg4 arg2 arg3

参数可以是任意数量且任意顺序。我想检查 arg4 字符串是否存在,无论参数编号如何。

我该怎么做?

谢谢,

bash
3个回答
5
投票

最安全的方法——处理参数中所有可能出现空格的方法等等——是编写一个显式循环:

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

1
投票

这是对命令行“参数”的典型解释,但我的大部分 bash 脚本都以以下方式开始,作为添加

--help
支持的简单方法:

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

主要缺点是,这也会由

request--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
参数(如果绝对没有给出参数)。


0
投票

也许这会有所帮助。

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

[ `echo $* | grep arg4` ] && echo true || echo false
© www.soinside.com 2019 - 2024. All rights reserved.