3

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

3 Answers 3

8
my_var=$(echo $line | cut -d" " -f3)

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

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

1 Comment

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.
1

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

2 Comments

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.
It works on my line on "versionCode = 11" (ignore the double quotes) and it prints 11.
1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.