18

I have some old scripts that I try to update. Some of the code condenses to:

 export X=`(echo "abc"; echo "def")` echo $X 

which gives the expected output:

 abc def 

Now the internet tells me backticks are out $() is what I need to use, but when I try:

export X=$((echo "abc"; echo "def")) 

X is not set and I get the error:

bash: echo "abc"; echo "def": syntax error: invalid arithmetic operator (error token is ""abc"; echo "def"") 

What am I doing wrong?

0

2 Answers 2

28

The $(( … )) syntax is an arithmetic expression.

What is missing is a space between the $( and the following (, to avoid the arithmetic expression syntax.

The section on command substitution in the shell command language specification actually warns for that:

If the command substitution consists of a single subshell, such as: $( (command) ) a conforming application shall separate the "`$(`" and '`(`' into two tokens (that is, separate them with white space). This is required to avoid any ambiguities with arithmetic expansion. 
1
  • 21
    It should be noted that `...` and $(...) start a subshell anyway, so the inner (...) are not needed (waste a process). You'd need the space in things like $( (...); (...) ) for instance (where the inner subshells may be needed). Commented Jan 29, 2014 at 11:46
15

Try export X="$(echo "abc"; echo "def")"

2
  • Thanks this does work, but requires more editing than the other solution. Commented Jan 29, 2014 at 11:37
  • 2
    +1 for including the quotes that are needed in most POSIX shells (ksh and bash being the only exceptions). Commented Jan 29, 2014 at 11:40

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.