首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用动态数组名检索值

使用动态数组名检索值
EN

Unix & Linux用户
提问于 2020-11-24 16:05:21
回答 2查看 198关注 0票数 0

我试图在for循环中检索一个值,但是每次都失败了。在这个脚本中,我必须为我的SSHFS挂载脚本声明远程路径。在下面的代码中,我将路径存储在一个用户数组中。在脚本的下面,这个用户被保存在$left中。所以空气是$left。不过,我不知道该怎么做。我最近的努力是,${!left[remote]}没有导致任何错误,只是导致了一个空值。

如何使用$left动态获取远程路径值?

代码语言:javascript
复制
#!/bin/bash

declare -A air
air[remote]="/home/air"

declare -A bhm
bhm[remote]="/home/bhm"

declare -A schwimserver3
schwimserver3[remote]="/var/www/clients/client1/web7/home/schwimserver3"


#echo ${air[remote]}

for u in $HOME/Remote/SSHFS/*
do
  if [ -d $u ]; then
    basename "$u" >/dev/null
    acct="$(basename -- $u)"
    
    IFS=- read -r left right <<< "$acct"
    if mountpoint "${HOME}/Remote/SSHFS/${acct}" >/dev/null; then
        printf '%b\n' "unmount ${right},fusermount -u /home/schwim/Remote/SSHFS/${right}"
    else
        printf '%b\n' "mount ${right},sshfs -o workaround=rename $left@$right:${!left[remote]} /home/schwim/Remote/SSHFS/${acct}"
    fi

  fi
done

耽误您时间,实在对不起!

EN

回答 2

Unix & Linux用户

回答已采纳

发布于 2020-11-24 20:26:00

问题是,您需要加倍解释数组。如果left="air",则$left不等于air[remote]。要执行双重替换,首先需要将$left插入到air中,然后将air[remote]解释为:$ air[remote]="/home/air" $ left="air" ; For clarity, lets make a temporary variable with the first substitution $ name_var='${'$left'[remote]}' ; Lets see the value of name_var $ echo $name_var ${air[remote]} ; Now, we need to force the shell to interpret this value $ eval echo $name_var /home/air ; Or, to store this in a value resolved_value=$( eval echo $name_var ),或者,作为一个一行程序:resolved_value=$( eval echo '${'$left'[remote]}' )

如何工作:诀窍在于创建$name_var:'${‘(带有单引号,而不是双引号)表示按原样使用字符(即不将它们解释为一个名为{ $left的变量,然后它的值"air“}将按原样使用这些字符。(同样,单引号而不是双引号) eval命令然后将字符(或变量$name_var的内容)替换到解释器中,并处理其结果,即代码中变量${air}的值“,您可以构建$resolved_value变量并将其放入脚本:printf '%b\n' "mount ${right},sshfs -o workaround=rename $left@$right:${resolved_value} /home/schwim/Remote/SSHFS/${acct}"中。

或者插入整个表达式:printf '%b\n' "mount ${right},sshfs -o workaround=rename $left@$right:$( eval echo '${'$left'[remote]}' ) /home/schwim/Remote/SSHFS/${acct}",尽管第一个选项对可读性更好。

票数 0
EN

Unix & Linux用户

发布于 2020-11-24 18:06:03

你为什么不倒置数组:

代码语言:javascript
复制
declare -A remotes=(
    [air]="/home/air"
    [bhm]="/home/bhm"
    [imserver3]="/var/www/clients/client1/web7/home/schwimserver3"
)

那你就用"${remotes[$left]}"吧。

这就是关联数组如此有用的原因:您不必使用动态变量名称。

若要使用动态名称,请使用bash版本4.3+并使用name:

代码语言:javascript
复制
declare -A foo=( [bar]=baz )
left=foo
declare -n ref=$left
echo "${ref[bar]}"

请参阅。手册中的3.4Shell参数

票数 0
EN
页面原文内容由Unix & Linux提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://unix.stackexchange.com/questions/621330

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档