2014-08-28 31 views
1

Debian testing,bash ...加载列表变成具有不同名称的单独变量

我试图从现有程序加载变量。

设置程序变量

xPROGS="$(echo -e "exiftool\nrsync\nxsel")" 

试图创建与X(项目名称)

echo "$xPROGS" | while read z; do x$z="$(whereis -b "$z" | awk '{print $2}')" ; done 

错误变量;

bash: xexiftool=/usr/bin/rsync: No such file or directory 
bash: xrsync=/usr/bin/rsync: No such file or directory 
bash: xxsel=/usr/bin/rsync: No such file or directory 

This works;

$ whereis -b rsync | awk '{print $2}' 

我无法实现成功更改变量名称。

有人可以请帮忙。

+1

h ttp://mywiki.wooledge.org/BashFAQ/006#Assigning_indirect.2Freference_variables – 2014-08-28 05:50:15

+0

错误消息被报告,因为bash不了解命令(x $ Z = ...)作为变量赋值。因此它被理解为一个名为“xexiftool =/usr/bin/rsync”的外部命令来加载和运行。 – Jdamian 2014-08-28 08:46:22

回答

2
$ cat t.sh 
#!/bin/bash 

progs=(exiftool rsync xsel) 

for prog in "${progs[@]}"; do 
     read -r _ "x${prog}" _ <<< "$(whereis -b "${prog}")" 
done 

echo "exiftool: [${xexiftool}]" 
echo "rsync: [${xrsync}]" 
echo "xsel:  [${xxsel}]" 
rsync命令将不会改变其位置

$ ./t.sh 
exiftool: [] 
rsync: [/usr/bin/rsync] 
xsel:  [] 
+0

对不起,代码应该是... $ echo“$ xPROGS”|同时读z; do x $ z =“$(whereis -b”$ z“| awk'{print $ 2}')”;完成。这是否会改变你的建议?谢谢。 – voiczed 2014-08-28 12:23:03

+0

@voiczed不,这会以习惯方式达到你的目的,并且不会不必要地分叉。 – 2014-08-28 14:04:50

+0

作品!谢谢。是否可以制作1行?这是行不通的:$ {progs [@]};请阅读-r _“x $ {prog}”_ <<<“$(whereis -b”$ {prog}“)”;完成 – voiczed 2014-08-28 18:16:34

1

@Etan赖斯纳提供从那里以下代码基于链接:

echo "$xPROGS" | while read z; do IFS= read -r "x$z" <<<$(whereis -b rsync | awk '{print $2}') ; done 

但我觉得,在文件系统树

RSYNC=$(whereis -b rsync); RSYNC="${RSYNC#* }"; echo "$xPROGS" | while read z; do IFS= read -r "x$z" <<<"$RSYNC" ; done 
+2

与bash,'声明“x $ z = $ RSYNC”'也适用。尽可能避免使用ALL_CAPS_VARNAMES(不要不小心使用'PATH = foo') – 2014-08-28 10:50:06

+0

非常抱歉。最初的'rsync'应该是“$ z”。我试图用你的建议,但回声$ xrsync是空白的。 – voiczed 2014-08-28 12:35:01

相关问题