2011-10-19 34 views
0

例如:壳牌:在var中存储命令供以后使用

并且使用命令时:

$ $CMD 
ls: /tmp/spaced\: No such file or directory 
ls: dir: No such file or directory 

不具有的功能:

CMD="ls /tmp/spaced\\ dir" 
CMD="ls \"/tmp/spaced dir\"" 
CMD="ls \"/tmp/spaced\\ dir\"" 
CMD='ls \"/tmp/spaced dir\"' 

而我需要的参数“/tmp/spaced dir”在变量中... 当然,目录“/tmp/spaced dir“确实存在。

回答

1

OK,发现使用eval一个解决方案:

$ CMD="ls /tmp/spaced\\ dir/" 
$ eval $CMD 
dir_in_spaced_dir 
$ 
1

你可能会谈论ALIAS

集的别名是这样的:

alias ls="ls /tmp/spaced" 

如果你需要“的/ tmp /间隔”将被存储在一个变种,只是这样做:

export MYVAR='/tmp/spaced' 
alias cmd="ls ${MYVAR}" 

如果ALIAS不允许的,只是把这个函数中的

function mydir(){ 
    ls ${MYVAR} 
} 
+0

不是别名,此命令可能只用于当前脚本 –

1

对于bash,数组是要走的路。

dir="/tmp/spaced dir" 
CMD=(ls "$dir") 
echo "cmd has ${#CMD[@]} words" 
"${CMD[@]}" # execute the command 
+0

+1实际适用于任何参数。 – l0b0