0

标题:标量变量内的 bash 参数扩展

我有一个 bash 脚本,它在两个文件之间运行差异。如果有差异,我希望它打印 statement1 和 statement2 它们很长,所以我将它们放入变量中,但 echo 语句不会扩展参数。这可以在bash中完成吗?

#!/bin/bash
set -x

source="/home/casper"
target="data/scripts"
statement1="There is a change in ${i}, please check the file"
statement2="or cp /home/casper/${i} /data/scripts/$i"

for i in file1 file2l file3 file4 file5  ; do
    sleep 1 ;
    if diff $source/$i $target/$i 2>&1 > /dev/null ; then
        echo " "
    else
        echo "$statement1 "
        echo "$statement2 "
    fi
done
exit 0

该脚本似乎有效 - 它在需要查找差异时找到了差异。然而,这是它打印出来的。

There is a change in , please check the file
or cp /home/casper/ data/scripts/

我想让它说

There is a change in file2, please check the file
or cp /home/casper/file2 /data/scripts/file2
4

2 回答 2

1

问题在于,$i当您定义statement1and时,它会被扩展statement2,而不是在您扩展它们时。使用 shell 函数输出文本。

notification () {
    echo "There is a change in $1, please check the file"
    echo "or cp /home/casper/$1 /data/scripts/$1"
}

source="/home/casper"
target="data/scripts"
for i in file1 file2l file3 file4 file5  ; do
    sleep 1 ;
    if diff "$source/$i" "$target/$i" 2>&1 > /dev/null ; then
        echo " "
    else
        notification "$i"
    fi
done
exit 0
于 2014-10-15T02:33:45.283 回答
0

这可以使用eval

TEMPLATE_MSG="aaa \${VALUE} ccc"
...
VALUE="bbb"
eval echo "${TEMPLATE_MSG}"

但我不推荐它,因为它eval是邪恶的 :-) 其他选项是使用模式替换:

TEMPLATE_MSG="aaa @1@ ccc"
...
VALUE="bbb"
echo "${TEMPLATE_MSG/@1@/${VALUE}}"

因此,您在消息中添加了一些独特的模式(例如@1@),然后,当您打印消息时,将其替换为变量的内容。

于 2014-10-14T23:49:20.023 回答