LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   how to nest commands (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-nest-commands-600275/)

new_2_unix 11-16-2007 09:29 PM

how to nest commands
 
hi,

in a simple script if a user wants to print the first argument entered as a param when running script, the script can be simply as follows:

Code:

#!/bin/sh
echo "arg1: "$1

$./myscript hello
$arg1: hello


however, lets say in my script i have to use a variable, instead of the number '1', so it would look like:

Code:

#!/bin/sh
x=1
echo "arg1: "$x

$./myscript hello
$arg1: 1

the problem here is that this will print on the console:

because $x evaluates to 1. my question is, how do i tell the script to first evaluate the $x to 1 and then do a $1?

i know this has to do with nesting the command, so that an inner command gets evaluated and the resulting value gets passed to the outer command and i've tried several approaches like $($x), ${$x}, $`$x`, $$x, but none of them works. any guidance as where i am going wrong will be helpful. thanks!

gilead 11-16-2007 09:48 PM

Depending which version of bash you're using, an indirect reference will do the job:
Code:

#!/bin/sh
x=1
echo "arg1: "$1
echo "Indirect reference: "${!x}


new_2_unix 11-16-2007 10:20 PM

yes, that did it!! thanks!


All times are GMT -5. The time now is 08:35 PM.