linux - 如何连接字符串并在 linux bash 脚本中显示格式化的字符串?

标签 linux string bash

我在下面写脚本

#!/bin/bash

str1="apple"
str2="banana"
str3="NA"
str4="lumia"
str5="nokia"

let maxarg=5

checkindex()
{
   while [ $maxarg -gt 0 ]
   do
        str="${str$maxarg}" //here is problem
        echo -e $str
        if [ "${str}" == "NA" ]
        then
            break
        fi

     ((maxarg--))
   done     

   printf "Index is %d\n" $maxarg
}

checkindex

当执行它时我得到了 str1,str2....Index is 0 输出但是我想打印的是 apple,banana....Index is 3 意味着捕获找到 NA 字符串的索引。使用 str="${str$maxarg}" 我尝试在 str 中重定向 str1,str2....str5 的输出,因为我不会使用任何 switch caseif..else 来比较每个字符串。 有帮助吗?

最佳答案

需要引用indirect expansion .换线

    str="${str$maxarg}" //here is problem

    tmp="str${maxarg}"   # This sets the variable tmp to str1 and so on
    str=${!tmp}          # This performs indirect expansion to retrieve
                         # the value of the variable name stored in tmp

应该让它工作。

关于linux - 如何连接字符串并在 linux bash 脚本中显示格式化的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21427797/

相关文章:

windows - 如何查看当前操作系统是Windows、Linux还是OSX?

linux - PER610 上的 IPMItool sel 命令未提供详细信息

c - 在 if 语句中使用 strcmp

linux - 无法在 Postgresql-10.0 上恢复数据库备份

linux - R-Car M3 MMC 初始化失败

java - 读取文本文件并比较文本 - Java

java - 对 .split() 在 Java 中的工作方式感到困惑

linux - 通过 bash myscript.sh 与 ./myscript.sh 启动 bash 脚本

bash - 如何通过间接引用从原始数组中删除元素

bash - 如何在 bash 中使用 while 循环