【问题标题】:load list into separate variables with varying names将列表加载到具有不同名称的单独变量中
【发布时间】:2014-10-21 21:09:22
【问题描述】:

Debian 测试、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

这行得通;

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

我无法成功更改变量名。

有人可以帮忙吗。

【问题讨论】:

  • 报错信息是因为 bash 不将命令 (x$Z=...) 理解为变量赋值。因此理解为一个名为“xexiftool=/usr/bin/rsync”的外部命令来加载和运行。

标签: bash variables dynamic


【解决方案1】:

@Etan Reisner 提供了以下代码所在的链接:

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

但是我感觉rsync命令不会改变它在文件系统树中的位置

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

【讨论】:

  • 使用 bash,declare "x$z=$RSYNC" 也可以。您应该尽可能避免使用 ALL_CAPS_VARNAMES(不要意外使用PATH=foo
  • 很抱歉。最初的“rsync”应该是“$z”。我试图用你的建议代替,但 echo $xrsync 是空白的。
【解决方案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}]"

 

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

【讨论】:

  • 对不起,代码应该是... $ echo "$xPROGS" |同时读取z;做 x$z="$(whereis -b "$z" | awk '{print $2}')" ;完毕 。这会改变你的建议吗?谢谢。
  • @voiczed 不,这以一种惯用的方式实现了您所追求的目标,并且没有不必要的分叉。
  • 有效!谢谢你。可以做1行吗?这不起作用: $ for prog in "${progs[@]}";阅读 -r _ "x${prog}" _
  • @voiczed 你先设置progs=(exiftool rsync xsel)了吗?或者,您可以使用for prog in exiftool rsync xsel; do read -r _ "x${prog}" _ &lt;&lt;&lt; "$(whereis -b "${prog}")" ; done
  • 是的,你不是说: progs="exiftool rsync xsel" 吗?感谢您的单班轮和帮助。干杯。 [已解决]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-28
  • 2023-03-13
  • 2013-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多