Shell script question

Hi all,

can you plz check whether the below code is correct & some inputs.
I need to read the below file and process it.

input :

 
/home/ibm/var.txt
 
urgent 
not urgent 
not needed.
 
#!/usr/bin/ksh
VAR=/home/ibm/var.txt
if [[ -s $VAR ]]
then
cat $VAR | while read VAR
do
if [[ $VAR = 'urgent' ]
then
echo "process";
else
echo "not process";
fi
done
  • Don't use the same variable for the file and the loop variable.
  • If opening a test with [[ make sure you close it with ]] .
  • Close the outer if with a fi .
  • don't use cat - redirect read 's input from $VAR.

As per your suggestion I have changed the all requested one. I am not sure abt the last point.

#!/usr/bin/ksh
VAR=/home/ibm/var.txt
if [[ -s $VAR ]]
then
cat $VAR | while read input
do
if [[ $input = 'urgent' ]]
then
echo "process";
else
echo "not process";
fi
done
fi

But getting error.

while read input
  do ....
  done < $VAR

WHAT error do you get?

---------- Post updated at 14:31 ---------- Previous update was at 14:30 ----------

Correct indentation always improves readability of programs/scripts/code.

the script works now.

Thanks a lot for your help rudic

#!/usr/bin/ksh
VAR=/home/ibm/var.txt
while read input
do
if [[ $input = 'urgent' ]];
then
echo "process| $input";
else
echo "not process";
fi
done > $VAR
 

I'm pretty sure the script given above does NOT work! You are redirecting stdout to your input file, and read from stdin, i.e. your terminal if run interactively.

I'd propose to exert utmost care if reproducing scripts/commands/data in these forums.

With properly indented code you won't miss a closing fi,
and you easily see that the while-block is redirected.

#!/bin/ksh
VAR=/home/ibm/var.txt
if [[ -s $VAR ]]
then
  # read from $VAR
  while read input
  do
    if [[ "$input" = "urgent" ]]
    then
      echo "process"
    else
      echo "not process"
    fi
  done < $VAR
fi

Note: the correct syntax for equality with a double bracket expression is:

if [[ $input == urgent ]]