Kunal
Kunal

Reputation: 511

Shell Script Not giving proper output

for i in `ls -lrt|grep ^d|cut -d ' ' -f 13-`
do
          cd $i
          ls
          cd ../
 done

In the above examples I am expecting the script to go into each directory, populate all the files of that directory, come out of it and then enter other directory and print its content. Please suggest whats wrong here.

Upvotes: 2

Views: 450

Answers (5)

glenn jackman
glenn jackman

Reputation: 246744

To iterate over only directories in the current directory, use the pattern */, so

for dir in */; do
    cd "$dir"
    do stuff
    cd ..
done

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203209

Never do any variation of "for file in ls" as it will fail for files with spaces in their names. All you need is:

find . -print

and if you want to do something with each file in the current directory then it's just

for file in *
do
    printf "Working on %s\n" "$file"
    <do stuff with "$file">
done

or for all subdirectories too then use xargs or:

find . -print |
while IFS= read -r file
do
    printf "Working on %s\n" "$file"
    <do stuff with "$file">
done

though the latter, like any pipe-based solution, will fail for files with newlines in their names.

Upvotes: 0

Tanmoy Bandyopadhyay
Tanmoy Bandyopadhyay

Reputation: 985

Please check if the field 13 is the desired field that is the last field of ls command's output. In my system it is the 9th field. So by I have changed your code to,

for i in `ls -lrt|grep ^d|cut -d ' ' -f9`
do
      echo  "Directory -$i"
      cd $i
      ls
      cd ../

done

It works fine after this change.

Also you can do it using other commands too like sed, awk. I did it using awk, but not hardcoded any field value (Used the internal variable NF - Number of fields, to get the last field, which is supposed to be the name of the directory).

#for i in `ls -lrt|grep ^d|cut -d ' ' -f9`
for i in `ls -lrt|grep ^d|awk '{print $NF}'`

do
      echo  "Directory -$i"
      cd $i
      ls
      cd ../

done

This also worked fine.

Upvotes: 2

Marc Cohen
Marc Cohen

Reputation: 3808

The cut command doesn't work properly because there are a variable number of spaces between each field in the ls -ltr output, due to the vagaries of ls formatting and variable length text fields. A more reliable way to parse the filename out of the ls directory listing would be to replace the cut command with awk '{print $9}', so the for loop should look like this:

for i in `ls -lrt|grep ^d| awk '{print $9}'`

Upvotes: 2

omniuni
omniuni

Reputation: 133

Do one of the following do what you are looking for?

ls *
ls * -r

Upvotes: 1

Related Questions