2

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

3
  • @bitbucket where is it outputting to? Or what's the output that I'm getting? Commented Feb 3, 2012 at 22:05
  • To expect a correct answer you need to supply the incorrect answer as a clue. Are you getting any output? Commented Feb 3, 2012 at 22:10
  • Please see BashFAQ/006. Commented Feb 4, 2012 at 15:08

5 Answers 5

4

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

That's it. I knew there had to be a way to do it without using variables.
2

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.

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.