0

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(

3
  • Didn't get your question? Can you clarify? You want that the result of echo is the contents of a? Remove the backslash!
    – rems
    Commented Feb 25, 2011 at 12:34
  • @rems I update question
    – osdyng
    Commented Feb 25, 2011 at 12:36
  • What are you really trying to accomplish? Commented Feb 25, 2011 at 17:29

4 Answers 4

2

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.
2

... What?

$ foo() { echo $a; }
$ a=42
$ echo $(foo)
42
6
  • @Ignacio Don't work, I update question
    – osdyng
    Commented Feb 25, 2011 at 12:37
  • Of course your first test doesn't work. You forgot to export the variable. Commented Feb 25, 2011 at 12:41
  • @Ignacio how can I do?
    – osdyng
    Commented Feb 25, 2011 at 12:45
  • With export a=5. Commented Feb 25, 2011 at 12:45
  • @Ignacio It work only if inner command expand variable. python don't expand output. I also need use eval.
    – osdyng
    Commented Feb 25, 2011 at 14:13
1
echo `eval foo`

Is this what you want?

2
  • echo eval $(./test) 5: command not found
    – osdyng
    Commented Feb 25, 2011 at 12:46
  • Should be "echo $(eval foo)" or as I wrote "echo `eval foo`".
    – rems
    Commented Feb 25, 2011 at 14:57
0

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .