Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 27 down vote accepted

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.
share|improve this answer
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). –  Stéphane Chazelas Jan 29 at 11:46

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

share|improve this answer
    
Thanks this does work, but requires more editing than the other solution. –  Harold Jan 29 at 11:37
2  
+1 for including the quotes that are needed in most POSIX shells (ksh and bash being the only exceptions). –  Stéphane Chazelas Jan 29 at 11:40

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.