Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I need parameter expansion after command substitution.

GNU bash, version 4.1.5(1)

$ foo() { echo \$a; }
$ a=5
$ echo $(foo)
$a

Is it possible?

test:

#!/bin/bash

echo $a

run:

a=5
echo $(./test)

if test:

#!/bin/bash

echo \$a

run:

echo $(./test)
$a

Don't work(

share|improve this question
    
Didn't get your question? Can you clarify? You want that the result of echo is the contents of a? Remove the backslash! –  rems Feb 25 '11 at 12:34
    
@rems I update question –  osdyng Feb 25 '11 at 12:36
    
What are you really trying to accomplish? –  Dennis Williamson Feb 25 '11 at 17:29
add comment

4 Answers 4

Order can't be changed without changing source code.

You can use eval:

eval echo $(foo)

man bash:

   The order of expansions is: brace expansion, tilde  expansion,  parame‐
   ter,  variable  and arithmetic expansion and command substitution (done
   in a left-to-right fashion), word splitting, and pathname expansion.
share|improve this answer
add comment

... What?

$ foo() { echo $a; }
$ a=42
$ echo $(foo)
42
share|improve this answer
    
@Ignacio Don't work, I update question –  osdyng Feb 25 '11 at 12:37
    
Of course your first test doesn't work. You forgot to export the variable. –  Ignacio Vazquez-Abrams Feb 25 '11 at 12:41
    
@Ignacio how can I do? –  osdyng Feb 25 '11 at 12:45
    
With export a=5. –  Ignacio Vazquez-Abrams Feb 25 '11 at 12:45
    
@Ignacio Thanks –  osdyng Feb 25 '11 at 12:50
show 2 more comments
echo `eval foo`

Is this what you want?

share|improve this answer
    
echo eval $(./test) 5: command not found –  osdyng Feb 25 '11 at 12:46
    
Should be "echo $(eval foo)" or as I wrote "echo `eval foo`". –  rems Feb 25 '11 at 14:57
add comment

Function:

$ a=5
$ foo() { echo \$a; }
$ foo
$a
$ eval echo $(foo)
5

Script:

#!/bin/bash
echo $a

Run:

$ a=5
$ ./test
$ export a
$ ./test
5

New script:

#!/bin/bash
echo 'echo $a'

Run:

$ a=5
$ ./test
echo $a
$ eval $(./test)
5

Python example:

$ a=5
$ python -c 'print "echo $a"'
echo $a
$ eval $(python -c 'print "echo $a"')

Another Python example:

$ a=5
$ python -c 'print "a=42"'
a=42
$ echo $a
5
$ declare $(python -c 'print "a=42"')
$ echo $a
42
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.