-->

bash命令替换使用变量(Bash Command Substitution with Variab

2019-09-23 11:13发布

我有一个建立了基于文件的列表上的命令,因此命令是建立在飞bash脚本。 构建它的飞行意味着它被保存在一个变量。 然后我要运行该命令,并输出存储在一个单独的变量。 当我使用命令替换尝试运行命令,它掷骰子了。 我怎样才能得到命令替换用命令在一个变量工作时,该变量利用管道?

这里是我的脚本:

# Finds number of files that are over 365 days old

ignored_files=( 'file1' 'file2' 'file3' )
path_to_examine="/tmp/"
newer_than=365

cmd="find $path_to_examine -mtime -$newer_than"
for file in "${ignored_files[@]}"; do
    cmd="$cmd | grep -v \"$file\""
done
cmd="$cmd | wc -l"
echo "Running: $cmd"
num_active_files=`$cmd`
echo "num files modified less than $newer_than days ago: $num_active_files"

输出,如果我运行该程序:

# ./test2.sh 
Running: find /tmp/ -mtime -365 | grep -v "file1" | grep -v "file2" | grep -v "file3" | wc -l
find: bad option |
find: [-H | -L] path-list predicate-list
# 

输出,如果我运行CMD:

# num=`find /tmp/ -mtime -365 | grep -v "file1" | grep -v "file2" | grep -v "file3" | wc -l`
# echo $num
10
# 

Answer 1:

您必须使用eval命令:

num_active_files=`eval $var`

这使您可以生成一个表达式bash的动态运行。

希望这有助于=)



文章来源: Bash Command Substitution with Variables