1

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
  • 3
    This causes quotes around |. So the command it actually tries to run is find /tmp/ -mtime -365 '|' grep -v '"file1"' '|' grep -v '"file2"' '|' grep -v '"file3"' '|' head '|' wc -l. You can see this by adding #!/bin/bash -x to the top of the file.
    – user650654
    Oct 4, 2012 at 0:04

1 Answer 1

4

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 =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.