1
我有一个bash脚本,它基于文件列表构建一个命令,因此命令可以实时构建。实时构建它意味着它被存储在一个变量中。然后我想运行该命令并将输出存储在一个单独的变量中。当我使用命令替换来尝试并运行该命令时,它会出现。当变量使用管道时,如何获得命令替换以便在变量中使用命令?带变量的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
#
这会引起'|'引号。所以它实际尝试运行的命令是'find/tmp/-mtime -365'|' grep -v'“file1”''|' grep -v'“file2”''|' grep -v'“file3”''|'头'|' wc -l'。您可以通过在文件顶部添加'#!/ bin/bash -x'来看到这一点。 – user650654