Search code examples
linuxshls

ls conditional in a linux script for loop


I'm trying to create a simple for loop that will take all the outputs of an ls command and put each output into a variable. so far i have

for i in ls /home/svn
do
    echo $i
done

but it gives me an error.


Solution

  • Because the ls needs to be executed:

    for i in $(ls ...); do
      echo $i
    done
    

    Also, you might want to consider shell globbing instead:

    for i in /home/svn/*; do
      echo $i
    done
    

    ... or find, which allows very fine-grained selection of the properties of items to find:

    for i in $(find /home/svn -type f); do
      echo $i
    done
    

    Furthermore, if you can have white space in the segments of the path or the file names themselves, use a while loop (previous example adjusted):

    find /home/svn -type f|while read i; do
      echo $i
    done
    

    while reads line-wise, so that the white space is preserved.

    Concerning the calling of basename you have two options:

    # Call basename
    echo $(basename $i)
    # ... or use string substitution
    echo ${i##*/}
    

    To explain the substitution: ## removes the longest front-anchored pattern from the string, # up to the first pattern match, %% the longest back-anchored pattern and % the first back-anchored full match.