1

我有一个 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
# 
4

1 回答 1

4

您必须使用以下eval命令:

num_active_files=`eval $var`

这允许您为 bash 生成动态运行的表达式。

希望这会有所帮助=)

于 2012-10-04T00:11:29.453 回答