我在下面写脚本
#!/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 case
或 if..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/