fali
fali

Reputation: 57

How to assign command output to a variable

I want to assign the ouput of the following command to a variable in shell:

${arr2[0]} | rev | cut -c 9- | rev 

For example:

mod=${arr2[0]} | rev | cut -c 9- | rev 
echo $mod

The above method is not working: the output is blank.

I also tried:

mod=( "${arr2[0]}" | rev | cut -c 9- | rev )

But I get the error:

34: syntax error near unexpected token `|'
line 34: `  mod=( "${arr2[0]}" | rev | cut -c 9- | rev )   '

Upvotes: 0

Views: 202

Answers (2)

fali
fali

Reputation: 57

mod=$(echo "${arr2[0]}" | rev | cut -c 9- | rev )   
echo "****:"$mod

or

mod=`echo "${arr2[0]}" | rev | cut -c 9- | rev`   
echo "****:"$mod

Upvotes: 0

mklement0
mklement0

Reputation: 437082

To add an explanation to your correct answer:

You had to combine your variable assignment with a command substitution (var=$(...)) to capture the (stdout) output of your command in a variable.

By contrast, your original command used just var=(...) - no $ before the ( - which is used to create arrays[1], with each token inside ( ... ) becoming its own array element - which was clearly not your intent.

As for why your original command broke:

The tokens inside (...) are subject to the usual shell expansions and therefore the usual quoting requirements.

Thus, in order to use $ and the so-called shell metacharacters (| & ; ( ) < > space tab) as literals in your array elements, you must quote them, e.g., by prepending \.

All these characters - except $, space, and tab - cause a syntax error when left unquoted, which is what happened in your case (you had unquoted | chars.)

[1] In bash, and also in ksh and zsh. The POSIX shell spec. doesn't support arrays at all, so this syntax will always break in POSIX-features-only shells.

Upvotes: 1

Related Questions