0

here is how i tried it

while IFS= read line 
do
    var=$(cut -d ":" -f 3 $line)
    if [ "$var" = "L2" ]
    then :here is my action:
    fi
done < myfile.txt

What i want to do is read a file line by line, read the third word of each line, and do a special action if the third word = a certaine string, i've tried a lot of syntax but it doesn't work. i've also tried to echo "$var" just to see if my variable get the right value, and it does. i don't know what to do anymore

  • 1
    if [[ "$var" == "L2" ]]. Also, depending on your "here is my action", awk maybe ideal for this. – Raman Sailopal Dec 04 '20 at 12:54
  • [What's the difference between single and double equal signs (=) in shell comparisons?](https://unix.stackexchange.com/a/72042/339347) – 0stone0 Dec 04 '20 at 12:56
  • `while read line; do var=$(cut ...)` is an anti-pattern. Do `while IFS=: read a b var d; do ...` and let `read` split the line for you. – William Pursell Dec 04 '20 at 13:05
  • As written, the code does *not* set `var` correctly (because `$line` isn't passed to `cut` correctly). I'd recommend putting `set -x` before this section, so you can get a better idea what's actually being executed as it runs. – Gordon Davisson Dec 04 '20 at 19:37

1 Answers1

0

It is better to use double brackets for if condition & for String comparison double equals (==)

And the line which has "cut" command wouldn't have worked. Please find below the corrected code which is working.

while IFS= read line
do
    echo "Line is $line"
    var=`echo $line | cut -d ":" -f 3`
    echo $var
    if [[ "$var" == "L2" ]]
    then
      echo "Some Action"
    fi
done < myfile.txt
  • Single-brackets are fine in this case (and more portable to non-bash shells), as long as the strings are properly quoted. Double-bracket conditional expressions have some more powerful features (and fewer syntax oddities), but they're not relevant here. The important thing is providing `$line` to the `cut` command properly. BTW, I'd recommend double-quoting `$line`, and using `$( )` instead of backticks. – Gordon Davisson Dec 04 '20 at 19:34