【问题标题】:Bash Script Variable SubstitutionBash 脚本变量替换
【发布时间】:2012-02-03 22:00:40
【问题描述】:

我正在尝试将一些文本组合到一个变量中并输出组合变量的值。例如:

testFILE=/tmp/some_file.log
function test_param {
echo $1
echo test$1
echo $(test$1) #this is where I want to output the value of the combined variable
}

test_param FILE

输出将是:

FILE
testFILE
/tmp/some_file.log  <-- this is what I can't figure out.

有什么想法吗?

如果我没有使用正确的术语,请纠正我。

谢谢, 贾里德

【问题讨论】:

  • @bitbucket 它输出到哪里?或者我得到的输出是什么?
  • 要获得正确答案,您需要提供错误答案作为线索。你有输出吗?
  • 请看BashFAQ/006

标签: linux bash variables substitution


【解决方案1】:

尝试以下方法:

#!/bin/bash
testFILE=/tmp/some_file.log
function test_param {
    echo $1
    echo test$1
    varName=test$1
    echo ${!varName}
}

test_param FILE

varName前面的!表示应该根据$varName的内容查找变量,所以输出为:

FILE
testFILE
/tmp/some_file.log

【讨论】:

    【解决方案2】:

    你的意思是:

    #!/bin/bash
    
    testFILE=/tmp/some_file.log
    function test_param {
    echo $1
    echo test$1
    eval "echo \$test$1"
    }
    
    test_param FILE
    

    输出:

    FILE
    testFILE
    /tmp/some_file.log
    

    【讨论】:

    • 就是这样。我知道必须有一种不使用变量的方法。
    【解决方案3】:

    试试这个:

    testFILE=/tmp/some_file.log
    function test_param {
        echo $1
        echo test$1
        foo="test$1"
        echo ${!foo}
    }
    

    ${!foo} 是间接参数扩展。它说取foo 的值并将其用作要扩展的参数的名称。我认为您需要一个简单的变量名;我试过${!test$1} 没有成功。

    【讨论】:

      【解决方案4】:

      使用${!varname}

      testFILE=/tmp/some_file.log
      function test_param {
          local tmpname="test$1"
          echo "$1 - $tmpname"
          echo "${!tmpname}"
      }
      
      test_param FILE
      

      输出:

      FILE - testFILE
      /tmp/some_file.log
      

      【讨论】:

        【解决方案5】:

        这对我有用。我都输出了结果,并将其作为另一个变量隐藏起来。

        #!/bin/bash
        
        function concat
        {
            echo "Parameter: "$1
        
            dummyVariable="some_variable"
        
            echo "$1$dummyVariable"
        
            newVariable="$1$dummyVariable"
        
            echo "$newVariable"
        }
        
        
        concat "timmeragh "
        
        exit 0
        

        输出是:

        Parameter: timmeragh
        timmeragh some_variable
        timmeragh some_variable
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-06-08
          • 1970-01-01
          • 2014-02-16
          • 1970-01-01
          相关资源
          最近更新 更多