bash变量用特殊字符的引用进行评估

时间:2014-06-07 14:34:57

标签: bash expression special-characters eval

下面是一个简单的bash脚本,用于测试rar文件中的少量密码。 当密码包含特殊字符(!)时,我看到选项(-p)完全用quote(')解析。

#!/bin/bash -x

pwd=`echo Sei{0..9}{0..9}b{0..9}axq!zx`
#pwd=Sei03b4axq!zx
file="test.rar"
for eachpwd in $pwd
do
    eval unrar x "$file" -p"$eachpwd" id 2>/dev/null 1>/dev/null
    c=$?
    if [ $c = 0 ]
        then echo "Success"
        exit
    fi
    echo $eachpwd $c
done

输出

+ for eachpwd in '$pwd'
+ eval unrar x test.rar '-pSei49b4axq!zx' id
+ c=10
+ '[' 10 = 0 ']'
+ echo 'Sei49b4axq!zx' 10

问题
如何进行编码,在eval期间,我没有得到unrar x test.rar '-pSei49b4axq!zx' id而是将unrar x test.rar -pSei49b4axq!zx id作为评估表达式

更新1
尝试下面的代码,但仍然在-p选项上的引号(!)拒绝让步。

passwords=( Sei{0..9}{0..9}b{0..9}axq!zx )
file=test.rar

for password in "${passwords[@]}"; do
    if unrar x "$file" -p"$password" id 2>/dev/null 1>/dev/null; then
        echo "Success"
        exit
    else
        echo $password failed.
    fi
done

结果

   + for password in '"${passwords[@]}"'
    + unrar x test.rar '-pSei21b0axq!zx' id
    + echo 'Sei21b0axq!zx' failed.
    Sei21b0axq!zx failed.
    + for password in '"${passwords[@]}"'
    + unrar x test.rar '-pSei21b1axq!zx' id

请注意我正在使用bash shell执行。

2 个答案:

答案 0 :(得分:2)

对于正在发生的事情,有几种可能的解释,其中没有一个值得探索,因为您不需要使用eval。此外,最好使用数组来保存密码,或者直接将大括号表达式放在for循环中,而不是创建单个字符串。

# I use single quotes on the very small chance history expansion
# is enabled, to protect the !. You almost certainly can drop them.
passwords=( Sei{0..9}{0..9}b{0..9}'axq!zx' )

for password in "${passwords[@]}"; do
    if unrar x "$file" -p "$eachpwd" id 2>/dev/null 1>/dev/null; then
        echo "Success"
        exit
    fi
done

答案 1 :(得分:1)

您所看到的只是set -x导致Bash执行的输出的常规消歧。 (请注意密码在echo的{​​{1}}输出中也是单引号。)问题(如果有的话)与调试输出中的单引号无关。

一般来说,你应该引用更多,而不是更少。除非您特别要求Bash对值执行通配符扩展和字拆分,否则请在变量周围使用双引号。

set -x

此外,反引号中的echo "$password failed" useless。已注释掉的作业更好,但确实如此;使用单引号来确保你得到一个文字字符串而不是别的。

echo

并且,正如其他人已经指出的那样,pwd='Sei49b4axq!zx' 不仅是多余的,而且可能是你遇到问题的原因(如果你确实是这样;你的问题实际上并没有解释你试图解决的问题)解决!)

相关问题