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
#
|
. So the command it actually tries to run isfind /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