保留Bash变量中的解释

时间:2013-09-04 13:51:33

标签: bash quoting interpretation

我正试图在Bash变量中保留解释。

实施例

当我在命令提示符下运行以下行时。

rm aaa 2>> error_file ; echo '<br><br>' >> error_file

我得到以下内容(这就是我想要的):

rm: cannot remove `aaa': No such file or directory

如果我将错误处理代码放入变量中,它就会爆炸。

ERROR_HAN="2>> error_file ; echo '<br><br>' >> error_file"
rm aaa $ERROR_HAN
rm: cannot remove `"2>>"': No such file or directory

我试过引用了很多方法,但没有运气。我似乎无法为变量的2>>部分保留解释。

3 个答案:

答案 0 :(得分:0)

使用eval

eval rm aaa ${ERROR_HAN}

答案 1 :(得分:0)

不要将命令放在变量中。改为使用函数:

rm_error() {
    rm "$@" 2>> error_file 
    echo '<br><br>' >> error_file
}

rm_error file1 file2 file3

另请参阅:BashFAQ/050: I'm trying to put a command in a variable, but the complex cases always fail!

答案 2 :(得分:0)

你将使用eval作为不安全的。

更好地将其重定向到块上,并使用进程替换:

{
    rm aaa
    # ... other commands
} 2> >(
    while read -r LINE; do
        echo "$LINE"
        echo '<br><br>'
    done >> error_file
)

另一种在结尾只写一次<br><br>的方法:

{
    rm aaa
    # ... other commands
} 2> >(
    if read -r LINE; then
        while
            echo "$LINE"
            read -r LINE
        do
            continue
        done
        echo '<br><br>'
    fi >> error_file
)

即使没有错误,这个也会写<br><br>,最后只写一次:

{
    rm aaa
    # ... other commands
} 2>> error_file
echo '<br><br>' >> error_file

请注意,如果您只使用rm之类的命令,则不必将其放在块中,只需rm aaa 2>> >( ...。而且我认为你只需要一行:

rm aaa 2>> >(read -r LINE && echo "$LINE"$'\n''<br><br>' >> error_file)

另:

EFILE=/path/to/error_file
rm aaa 2> >(read -r LINE && echo "$LINE"$'\n''<br><br>' >> "$EFILE")

特定于命令的功能:

EFILE=/path/to/error_file

function log_error_to_file {
    read -r LINE && echo "$LINE"$'\n''<br><br>' >> "$EFILE"
}

rm aaa 2> >(log_error_to_file)
another_command 2> >(log_error_to_file)

多行:

function log_error_to_file {
    while read -r LINE; do
        echo "$LINE"
        echo '<br><br>'
    done >> error_file
}
相关问题