linux - 如何通过字符串组装变量

标签 linux shell

我有以下 shell 脚本,假设它的名称为 test.sh

#!/bin/bash
b_x='it is the value of bx'
c_x='it is the value of cx'

case "$1" in
    "b")
       echo $1_x    # it's doesn't work; I want to echo $b_x
       ;;
     "c")
       echo $1_x   # it's doesn't work; I want to echo $c_x
       ;;
esac

然后我想调用脚本;

./test.sh  b    # I want the output is "it is the value of bx"
./test.sh  c    # I want the output is "it is the value of cx"

最佳答案

你不需要case。只需使用间接变量名扩展:

b_x='it is the value of bx'
c_x='it is the value of cx'

var="${1}_x"
echo "${!var}"

然后运行它:

$> bash test.sh b
it is the value of bx

$> bash test.sh c
it is the value of cx

关于linux - 如何通过字符串组装变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38371740/

相关文章:

linux - 在单个 Linux 命令操作系统脚本中使用某些条件重命名多个文件夹中的所有文件。

linux - 如何准确显示命令输出的 10 行

java - 如何确定和使用 Linux shell 脚本中的实际 java 路径

c++ - 是否可以在 C++ 代码中使用 Linux Perf 分析器?

java - 64 位 java glibc 依赖项,不兼容

shell - 如何在 korn shell 中转义逗号?

shell - 使用 shell 编写脚本 - Asterisk

linux - 使用 Apache 时,我应该将工作区目录放在哪里?

安装模块时出现 Python ImportError [Ubuntu]

python - 根据 Linux 文件系统层次结构标准,放置 Python 虚拟环境的正确位置在哪里?