Bash Command Substitution with Variables

2019-06-05 01:00发布

I have a bash script that builds a command based on a list of files so the command is built on the fly. Building it on the fly means it gets stored in a variable. I then want to run that command and store the output in a separate variable. When I use command substitution to try and run the command, it craps out. How can I get command substitution to work with a command in a variable when that variable utilizes pipes?

Here is my script:

# 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"

Output if I run that program:

# ./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
# 

Output if I run that cmd:

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

1条回答
来,给爷笑一个
2楼-- · 2019-06-05 01:29

You must use the eval command:

num_active_files=`eval $var`

This allows you to generate an expression for bash to run dynamically.

Hope this helps =)

查看更多
登录 后发表回答