如何使用单引号或双引号检测参数?

时间:2017-03-19 14:25:46

标签: linux shell

在shell(受限制的Ksh)中:

script1.sh "arg1 arg" arg2 'agr3 arg4' ...

(参数的数量和带引号的args的顺序是随机的)

如何在脚本中检测我们是否在arg列表中使用单引号或双引号?

更新:如果引用了args:

,则下一个代码找不到引号

if [[ "$#" == *"\""* ]]; then echo "Quotes not accepted" >&2 exit 1 fi

1 个答案:

答案 0 :(得分:2)

在命令(在本例中为您的脚本script1.sh)被调用之前,shell会解释引号。我不确定为什么你的脚本想要知道是否引用了参数。为了实现您的目标,您需要将您的参数放在两组引号中 - 使用双引号来保护单引号和单引号以保护双引号,如下所示:

script1.sh '"arg1 arg"' arg2 "'arg3 arg4'" ...

在这种情况下,脚本会看到:

$1 => "arg1 arg"  # double quotes are a part of the string
$2 => arg2
$3 => 'arg3 arg4' # single quotes are a part of the string

然后脚本可以检查引号:

[[ "$1" = \"*\" ]] && echo "argument 1 has double quotes"
[[ "$3" = \'*\' ]] && echo "argument 3 has single quotes"

另见: