LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   a question to a special ls (https://www.linuxquestions.org/questions/linux-newbie-8/a-question-to-a-special-ls-749707/)

Lazybaer 08-23-2009 01:58 PM

a question to a special ls
 
Hi

Can anyone explain me in detail the follwing instructions (line 1 and 2 only).

ls | \
while IFS= read filename
do
(something)
done

Thanks in advance.
Regards
Lazy

colucix 08-23-2009 02:08 PM

Hi and welcome to LQ.

The code you've posted executes a while loop taking input from the ls command. This is a method to read a block of text line by line and execute some actions over each line. More in details the ls command list the files in the current directory and pipe this list to the while loop. The backslash at the end of the line is not really necessary. In shell programming it simply means that the statement continues on the next line, but the pipe acts in the same way.

The while loop just reads the input and assigns every line to the shell variable "filename". The syntax is:
Code:

while command
do
  <commands here>
done

where the command in the code above is:
Code:

IFS= read filename
the IFS= is an assignment to an environment variable, whose value will be used just for the execution of the command itself, without affecting other statements. IFS is the Input Field Separator and its default value is space/tab/newline. The statement
Code:

IFS=
just assigns the null string to IFS. This is a method to manage file names containing blank spaces. A little more clear now?

catkin 08-23-2009 03:01 PM

Quote:

Originally Posted by colucix (Post 3654680)
This is a method to manage file names containing blank spaces.

A null (=empty) IFS works just the same as the default IFS so the sample code effectively ensures that any non-standard value of IFS does not cause things to go awry. The only reason for using it would be if IFS had been set to some other value earlier which the programmer wanted to keep for later. File names with spaces will be assigned to $filename by the read command with both IFS null and the default IFS.

Lazybaer 08-23-2009 03:37 PM

Thanks guys for the prompt replies - it's quite clear now. In the mean time my recursive script works as it should. Regards - Lazy


All times are GMT -5. The time now is 03:00 PM.