Bash Command Substitution with Variables
Asked Answered
L

1

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
# 
Lawgiver answered 3/10, 2012 at 23:57 Comment(1)
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.Schnauzer
E
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 =)

Erroneous answered 4/10, 2012 at 0:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.