1

I'm new shell scripting and have a quick question about my code. This works:

x=2
y=4
z=6
x=$(( $x-1 ))
y=$(( $y-2 ))
z=$(( $z-3 ))
echo $x $y $z

$ script.sh
1 2 3

And this works:

n=2,4,6
IFS=$',' read x y z <<< $n
echo $x $y $z

$ script.sh
2 4 6

But this results in a syntax error:

n=2,4,6
IFS=$',' read x y z <<< $n
x=$(( $x-1 ))
y=$(( $y-2 ))
z=$(( $z-3 ))
echo $x $y $z

$ script.sh
syntax error in expression (error token is "4 6-1 ")
2 4 6 -2 -3

Could someone please explain why this doesn't work and what the syntax error means? Thanks!

bggarchow
  • 48
  • 1
  • 5
  • Your code worked for me. You can find out a lot by using bash's debugging option (add `set -x` at the beginning of your file). – xificurC Sep 17 '14 at 14:18

1 Answers1

1

Problem is not using quotes in read command.

Use it as:

IFS=$',' read x y z <<< "$n"

When you use it without quotes as IFS=$',' read x y z <<< $n then only variable x gets value as: 2 4 6 but y and z remain empty hence next set of statements cause error.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    This is actually a bug that was fixed in 4.3, as the `IFS` should only apply to the `read`, not the here-string. – chepner Sep 17 '14 at 14:28
  • Thanks for the quick answer! Qouting $n does make the 3rd code block work. But $n is unquoted in the 2nd code block and $x $y and $z get their values. Why is this? – bggarchow Sep 17 '14 at 14:32
  • Use your echo as `echo "[$x] [$y] [$z]"` to see what variables are populated after `$n` is unquoted. – anubhava Sep 17 '14 at 14:34
  • [2 4 6] [] [] Ok, I get it now. – bggarchow Sep 17 '14 at 14:41