For or while?


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting For or while?
# 1  
Old 05-04-2016
For or while?

Hi, I've a file containing file names along with their path. I need a script which checks each line in that file which has file names along with their path and display if a particular file exists or not.
file.txt which has file names along with their path
Code:
/path1/to/file/file_name1
/path2/to/file/file_name2
/path3/to/file/file_name3
/path4/to/file/file_name4

I tried with this below mentioned code, but unable to get desired output.
Code:
for i in $(cat file.txt)
do
ls -lrt $i
done

Requesting guidance in this regard. Thanks.
# 2  
Old 05-04-2016
ls * shows a listing of the current working directory. It does not include the paths given in your file.
Why don't you read the file line by line in a while loop and use shell parameter expansion for the existence tests?

What be the "desired output"?
# 3  
Old 05-04-2016
Thanks for your reply RudiC. I just tried with do-while loop.
Code:
#!/bin/ksh
while read i
do
ls -lrt $i
done < files.txt

I'm getting desired output of long listing of files via "ls -lrt" command. But i need to upgrade this one step ahead by including probably an if-else condition (pls correct if i'm wrong) to check if a particular file exists or not. Could you please suggest?
# 4  
Old 05-04-2016
Quote:
Originally Posted by sam_bd
to check if a particular file exists or not. Could you please suggest?
use test operator.
Code:
man test
     -s file                     True if file exists  and  has  a
                                 size greater than zero.

Code:
      if [ ! -s /path/to/file/name.dat ]   
      then
                echo "No files in the DIR!"
                exit 1 # if you want to exit from the script or can use continue
                # continue   ## un-comment if you want to continue instead of exit and comment to above line
      fi

# 5  
Old 05-04-2016
Why isn't the diagnostic output from ls sufficient to let you know that a file doesn't exist? If for some reason, you do need to test for a file's existence (without caring what its size is):
Code:
#!/bin/ksh
while read -r file
do	if [ -e "$file" ]
	then	printf 'file "%s" exists.\n' "$file"
		ls -lrt "$file"
	else	printf 'file "%s" does not exist.\n" "$file"
	fi
done < files.txt

# 6  
Old 05-04-2016
Please don't edit any post after someone (me) referenced it in another post, thus pulling the rug from under their feet...

What does ls -lrtgive you that ls -l wouldn't?

Try
Code:
while read FN
  do [ -e "$FN" ] && ls -l "$FN" || echo "$FN does not exist"
  done < files.txt

# 7  
Old 05-04-2016
RudiC, Don C, saps19 Thanks each one of you. I did try looking at your posts. This is good learning for me. Thanks indeed for giving direction to think.

Login or Register to Ask a Question

Previous Thread | Next Thread
Login or Register to Ask a Question