如何将命令存储在shell脚本中的变量中?我想在一个变量中存储一个以后使用的命令(不是命令的输出,而是命令本身)。我有一个简单的脚本如下:command="ls";echo "Command: $command"; #Output is: Command: lsb=`$command`;echo $b; #Output is:
public_html REV test... (command worked successfully)然而,当我尝试一些更复杂的东西时,它就失败了。例如,如果我command="ls | grep -c '^'";产出如下:Command: ls | grep -c '^'ls: cannot access |: No such file or directory
ls: cannot access grep: No such file or directory
ls: cannot access '^': No such file or directory知道我如何将这样的命令(使用管道/多个命令)存储在变量中以供以后使用吗?
3 回答
慕码人2483693
BashFAQ-50
TA贡献1860条经验 获得超9个赞
eval
BashFAQ-50-我试图在变量中放一个命令,但是复杂的情况总是失败的。
"${arr[@]}"
IFS
cmdArgs=()cmdArgs=('date' '+%H:%M:%S')
declare -p
declare -p cmdArgs declare -a cmdArgs='([0]="date" [1]="+%H:%M:%S")'
"${cmdArgs[@]}"23:15:18
bash
cmd() { date '+%H:%M:%S'}
cmd
sh
sh
# POSIX sh# Usage: sendto subject address [address ...]sendto() { subject=$1 shift first=1 for addr; do if [ "$first" = 1 ]; then set --; first=0; fi set -- "$@" --recipient="$addr" done if [ "$first" = 1 ]; then echo "usage: sendto subject address [address ...]" return 1 fi MailTool --subject="$subject" "$@"}
斯蒂芬大帝
TA贡献1827条经验 获得超8个赞
var=$(echo "asdf")echo $var# => asdf
stored_date=$(date)echo $stored_date# => Thu Jan 15 10:57:16 EST 2015# (wait a few seconds)echo $stored_date# => Thu Jan 15 10:57:16 EST 2015
stored_date=`date`echo $stored_date# => Thu Jan 15 11:02:19 EST 2015# (wait a few seconds)echo $stored_date# => Thu Jan 15 11:02:19 EST 2015
$(...)
stored_date=$(eval "date")echo $stored_date# => Thu Jan 15 11:05:30 EST 2015# (wait a few seconds)echo $stored_date# => Thu Jan 15 11:05:30 EST 2015
eval
stored_date="date" # < storing the command itselfecho $(eval "$stored_date")# => Thu Jan 15 11:07:05 EST 2015# (wait a few seconds)echo $(eval "$stored_date")# => Thu Jan 15 11:07:16 EST 2015# ^^ Time changed
stored_date="date -u"# ...
eval
- 3 回答
- 0 关注
- 527 浏览
添加回答
举报
0/150
提交
取消