i'm reading a few variables from a file using

while read a b c; do
  (something)
done < filename

is there an elegant way to skip a variable (read in an empty value), i.e. if I want a=1 b= c=3, what should I write in the file?

Right now i'm putting

1 "" 3

and then use

b=$(echo $b | tr -d \" )

but this is pretty cumbersome, IMHO

any ideas?

link|improve this question

80% accept rate
feedback

2 Answers

up vote 2 down vote accepted

With a blank field:

1 3

You can do:

if [[ -z c ]]
then
    c=b
    b=
fi

If your data is comma delimited, you can also do:

while IFS=, read a b c

(but you'll have problems if your fields contain commas, as you may in your current version if they contain quotes):

1,,3

Also, in your version instead of using tr, you can do:

b=${b//\"\"}

but you can eliminate that step altogether using the following with your current data format:

while IFS='"' read a b c

however, comma-delimited fields is a more common format.

link|improve this answer
this would work only if there is only one optional variable, but I have more than one, unfortunately. But +1 for getting rid of tr in any case ;) – Aleksandar Ivanisevic Mar 26 '10 at 8:23
@Aleksandar: The comma-delimited version would work for any number of fields. 1,,3,4,5,,7 – Dennis Williamson Mar 26 '10 at 9:49
yup, you are right, thanks ;) – Aleksandar Ivanisevic Mar 26 '10 at 19:55
feedback

I am not sure if I understood what you want but you can skip certain values of the iteration (be it while, for or whatever) with continue and even stop the iteration with break

while read a b c ;do 
   if [[ $b == 0 || $c == 0 || $a == 0 ]];then
      continue
   fi      
   (makelovenotwar)
done < /foo/bar
link|improve this answer
No, by "skipping" I meant putting an empty value into a variable – Aleksandar Ivanisevic Mar 26 '10 at 8:20
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.