2012-10-03 155 views
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 
# 
+3

這會引起'|'引號。所以它實際嘗試運行的命令是'find/tmp/-mtime -365'|' grep -v'「file1」''|' grep -v'「file2」''|' grep -v'「file3」''|'頭'|' wc -l'。您可以通過在文件頂部添加'#!/ bin/bash -x'來看到這一點。 – user650654

回答

4

必須使用eval命令:

num_active_files=`eval $var` 

這使您可以生成一個表達式讓bash動態運行。

希望這有助於=)