bash命令替换使用变量 [英] Bash Command Substitution with Variables

查看:149
本文介绍了bash命令替换使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个建立了基于文件的列表中的命令,以便命令是建立在飞bash脚本。构建它的飞行意味着它被保存在一个变量。然后,我要运行该命令,输出存储在一个单独的变量。当我使用命令替换尝试运行命令,它掷骰子了。我怎样才能得到命令替换在一个变量与命令工作时可变利用管?

下面是我的脚本:

 #查找因为在365天旧文件数ignored_files =('文件1'文件2''文件3')
path_to_examine =/ tmp目录/
newer_than = 365CMD =$找到-mtime path_to_examine - $ newer_than
在$ {ignored_files [@]}的文件;做
    CMD =$ CMD | grep的-v \\$文件\\
DONE
CMD =$ CMD |厕所-l
回声运行:$ CMD
num_active_files =`$ cmd`
回声修改少于$ newer_than天前NUM文件:$ num_active_files

输出如果我运行该程序:

 #./test2.sh
跑步:找的/ tmp / -mtime -365 | grep的-v文件1| grep的-v文件2| grep的-v文件3|厕所-l
发现:坏的选择|
发现:[-H | -L]路径列表predicate名单

输出如果我运行CMD:

 #NUM =`找到的/ tmp / -mtime -365 | grep的-v文件1| grep的-v文件2| grep的-v文件3| WC -l`
#$回声NUM
10


解决方案

您必须使用评估命令:

  num_active_files =`$ EVAL var`

这允许你生成一个前pression对于bash动态运行。

希望这有助于=)

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
# 

解决方案

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

这篇关于bash命令替换使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆