简体   繁体   中英

Bash Script Variable Substitution

I'm trying to combine some text to a variable and output the value of the combined variable. For example:

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

Output would be:

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

Any ideas?

If I'm not using the correct terminology please correct me.

Thanks, Jared

Try the following:

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

test_param FILE

The ! before varName indicates that it should look up the variable based on the contents of $varName , so the output is:

FILE
testFILE
/tmp/some_file.log

do you mean this:

#!/bin/bash

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

test_param FILE

output:

FILE
testFILE
/tmp/some_file.log

Try this:

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

${!foo} is an indirect parameter expansion. It says to take the value of foo and use it as the name of a parameter to expand. I think you need a simple variable name; I tried ${!test$1} without success.

Use ${!varname}

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

test_param FILE

Output for that:

FILE - testFILE
/tmp/some_file.log

This worked for me. I both outputted the result, and stashed it as another variable.

#!/bin/bash

function concat
{
    echo "Parameter: "$1

    dummyVariable="some_variable"

    echo "$1$dummyVariable"

    newVariable="$1$dummyVariable"

    echo "$newVariable"
}


concat "timmeragh "

exit 0

The output was:

Parameter: timmeragh
timmeragh some_variable
timmeragh some_variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM