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(

osdyng
  • 1,872
  • 1
  • 13
  • 10

4 Answers4

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.
ooshro
  • 10,874
  • 1
  • 31
  • 31
2

... What?

$ foo() { echo $a; }
$ a=42
$ echo $(foo)
42
Ignacio Vazquez-Abrams
  • 45,019
  • 5
  • 78
  • 84
1
echo `eval foo`

Is this what you want?

rems
  • 2,240
  • 13
  • 11
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
Dennis Williamson
  • 60,515
  • 14
  • 113
  • 148