在bash中使用if语句中的特殊字符

时间:2013-10-25 19:16:10

标签: linux bash

我不熟悉bash脚本。我写了一个脚本检查参数。代码是:

for (( i=1; i<=4; i++ ))
do
        if ! [[ "$"$i =~ .*[^0-9].* ]]; then
                echo "bad input was $i"
        fi
done

实际上我想分割非数字参数,但似乎“$”$ i是错误的,因为答案总是真或假,不依赖于参数。 任何人都可以告诉我这是什么错误吗?

3 个答案:

答案 0 :(得分:3)

您似乎尝试使用间接参数扩展。

for (( i=1; i<=4; i++ ))
do
    if ! [[ ${!i} =~ .*[^0-9].* ]]; then
        echo "bad input was $i"
    fi
done

然而,直接迭代参数,而不是超过它们的位置更简洁:

for arg in "${@:1:4}"; do
    if ! [[ $arg =~ .*[^0-9].* ]]; then
        echo "bad input was $arg"
    fi
done

答案 1 :(得分:1)

如果情况应该是这样的:

if [[ ! "$i" =~ [^0-9] ]]; then

或删除2个底片:

if [[ "$i" =~ [0-9] ]]; then

或者使用glob:

if [[ "$i" == *[0-9]* ]]; then

这意味着$i包含数字0-9

更新:根据您的评论,您似乎正在寻找BASH变量间接,例如此脚本check-num.sh

#!/bin/bash
for (( i=1; i<=$#; i++ )); do
    [[ "${!i}" != *[0-9]* ]] && echo "bad input was ${!i}"
done

您可以将此脚本运行为:./check-num.sh 1 2 x 4 a

注意这里如何使用${!i}语法来访问名为BASH变量间接的变量$1, $2, $3等。 您不应将$$i用于此目的。

根据BASH手册:

  

If the first character of parameter is an exclamation point, a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself.

答案 2 :(得分:1)

使用类似的东西:

for i in "$@"; do
     [[ $i =~ .*[^0-9].* ]] || echo "bad input was $i"
done

N.B:没有必要使用[[内部指令。]

在变量周围使用双引号。