views:

215

answers:

3

Hey,

A really simple shell script question. I have a file with something like this:

var "aaaaa"
var "bbbbb"
...

Now, how can I assign the string in quotes to a variable? This is what I have now (but I'm missing the assign part...):

while read line
do
  echo $line | cut -d" " -f3
done

which prints what I want... how do I save it to a variable?

Thanks

A: 

Depends on a shell.

Bourne and derivatives, you do

my_var_name=expression

C shell and derivatives, you do

setenv my_var_name expression

If you want to save the output of a command (e.g. "cut xyz"), you use backticks operator as your expression:

my_var_name=`echo $line | cut -d" " -f3`

I think that bash also supports $() but not sure of a difference from backticks - see section 3.4.5 from http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_04.html

DVK
I'm using bash.You mean something like: my_var=$line | cut -d" " -f3? Doesn't seem to work. Prints nothing.And yes, assigning them to the same variable on each loop would be fine.
pns
@DVK: Why `$()`? - http://mywiki.wooledge.org/BashFAQ/082
Dennis Williamson
+2  A: 
my_var=$(echo $line | cut -d" " -f3)

You need to execute the command. That is what the $() is for.

frankc
In general, you should quote the command substitution and the variable expansion to preserve whitespace: `my_var="$(echo "$line" | cut -d" " -f3)"`. This command is already splitting on the space character, but it may also be important to preserve tabs, newlines, or anything else that might be in IFS.
Chris Johnsen
+1  A: 

you don't have to use external cut command to "cut" you strings. You can use the shell, its more efficient.

while read -r a b
do
  echo "Now variable b is your quoted string and has value: $b"
done <"file"

Or

while read -r line
do
  set -- $line
  echo $2
done <"file"
ghostdog74