0

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 )   '
4
  • What's in $arr2? How do you assign it? How exactly is it not working (error message, expected vs. actual output)? Commented Apr 3, 2015 at 22:03
  • in $arr2[0] i have a long string and i am trimming last 8 characters. if i echo ${arr2[0]} | rev | cut -c 9- | rev, i get what i want. but i want to assign the outcome to a variable. right now echo $mod give me blank, nothing. I assign by: arr2=($line) Commented Apr 3, 2015 at 22:09
  • I GOT IT, mod=$(echo "${arr2[0]}" | rev | cut -c 9- | rev ) echo "****:"$mod Commented Apr 3, 2015 at 22:35
  • 1
    @fali You should submit and accept your own answer to this question. Commented Apr 3, 2015 at 23:15

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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

or

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

3 Comments

accept this answer so new people do not try to answer
I can't accept my own answer. "It say i can't accept my own answers in 18 hrs."
You are right. stackoverflow.com/help/self-answer tells you have to wait 48 hours.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.