Assigning command output to a shell variable

Richeek picture Richeek · Mar 30, 2012 · Viewed 26k times · Source

I am trying to assign output of a cut command to a variable, however I am running into a strange problem. I am using tcsh shell.

$echo $0
tcsh

This is the command I am running:

$set a=`cut -f2 -d' ' test.txt`
Missing }.    //This is the output I am getting

Now the file is real simple (well this is the not the file I was working on but I reduced the problem to this.)

Test.txt:

{ {corner

Thats it! This is the file. If I change the file to this:

{ {corner}

Statement works but "a" gets the following value:

$echo $a
corner   //Please note its not {corner} but corner

Hence I think that shell is trying to execute {corner as a command and since its missing the closing brace shell complains. Does anyone have any idea why its showing this behavior? My understanding is that it should just assign the output of cut to the variable but looks like its assigning it recursively! Newbie

Answer

ring bearer picture ring bearer · Mar 30, 2012

You have to wrap it around double quotes

set a="`cut -f2 -d' ' test.txt`"

Same applies to uses such as echo

echo "$a"

Output

{corner