Why doesn’t my loop over the output of ls work?

I am trying to feed Directory names into a for loop. My code is as follows:

td='/Test/TopDir/'
cd "$td" 
for x in $(ls -d */ | cut -f1 -d'/'); do
  echo x=$x
done

The top directory I run this on looks like this when running an ls command:

ls -l
drwxrwxrwx    4 Jason    users         4096 May  6 06:36 2014-02-02 - Jebby (
drwxrwxrwx    3 Jason    users         4096 May  6 06:09 2014-02-04 - Jebby (
drwxrwxrwx    2 root     root          4096 May  6 06:09 @eaDir
-rw-r--r--    1 Jason    users      3956225 Jan 26 10:17 DSC01062.JPG
-rw-r--r--    1 Jason    users      3927603 Jan 26 10:18 DSC01063.JPG

The results of my for loop is as follows:

x=2014-02-02
x=-
x=Jebby
x=(
x=2014-02-04
x=-
x=Jebby
x=(
<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f189ccb19490b59883">[email protected]</a>

As you can see the for loop is breaking the directory names into sub-pieces after each space. In this example I only want the For Loop to execute three time with the three directories:

  1. 2014-02-02 – Jebby (
  2. 2014-02-04 – Jebby (
  3. @eaDir

What am I doing wrong?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Avoid parsing the output (or at least the filename portion) of ls in shell scripts if at all possible. It will always give issues with word-splitting where filenames contain whitespace.

If you want to iterate over directories you can do that using a simple shell glob i.e.

for d in */; do 
  echo "$d"
done

The ls command should only be used for displaying directory listings in human-readable form in the terminal.

Method 2

Using @mikserv’s suggestion, you can do

cd /Test/TopDir/
set -- "$PWD" */
cd /somewhere/else
td=$1 ; shift 
for x; do
  echo x="${td}/$x"
done


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x