Question

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.

Was it helpful?

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.

OTHER TIPS

You don't need to use ls to go over files in this case, the following will do the job: for i in /home/svn/*; do echo $i; done

You want to assign the output of the ls command to i, so you need to enclose it in backticks or the $() operator:

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

That's because you're doing it wrong in the first place.

for i in /home/svn/*
do
  echo "$i"
done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top