Sunny1985
Sunny1985

Reputation: 91

while loop not working in shell

Can anyone help me with the below. I do not understand what is wrong, Not getting any output. My requirement is to read a file and check if it's not empty and to print the content line by line.

   #!/bin/ksh
   echo " enter file name "
   read $file
   if [ -f "$file" ] && [ -s "$file" ]
    then 
   echo " file does not exist, or is empty "
      else
   while IFS='' read -r line || [[ -n "$file" ]];do
      echo "$line"
   done
   fi

Upvotes: 0

Views: 56

Answers (1)

John
John

Reputation: 34

read $file should be read file

Your comparison logic is backwards. The comparison if [ -f "$file" ] && [ -s "$file" ] is 'if the file is a regular file and not empty go into error case'. You want 'if the file is not regular or the file is empty go into error case' if [ -f "$file" ] -eq 0 || [ -s "$file" ] -eq 0.

Per ksh file read should be

 while IFS='' read -r line 
   do
      echo "$line"
   done < "$file"

Further Reading On ksh redirection

Upvotes: 1

Related Questions