簡體   English   中英

如何連接字符串並在linux bash腳本中顯示格式化字符串?

[英]How concatenate strings and display that formated string in linux bash script?

我寫下面的腳本

#!/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

當exicuting它我得到str1,str2....Index is 0輸出但我想打印apple,banana....Index is 3意味着捕獲NA字符串找到的索引。 使用str="${str$maxarg}"我試圖在str重定向str1,str2....str5的輸出,因為我不打算使用任何switch caseif..else來比較每個字符串。 有幫助嗎?

您需要參考間接擴展 替換線

    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

應該讓它發揮作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM