bash shell loop directory listing with white spaces issue

Associate
Joined
12 Nov 2008
Posts
1,220
I'm trying to get a bash script working that uses a for loop to get the files within a directory and then processes each of them. A rather simple task, but when some files have white spaces in them (e.g. another file), I then get multiple entries in the list for each word in the file name;
another
file

I'll try to give a better idea of what is going on with example of how the current script gets the list:

workdir='/dir/subdir/'

for each filename in $(ls workdir); do

process the $filename #tar rename etc.

done

However using the ls command of the directory to pass it into a variable, gives me the issue above in that it can't deal with filenames that have whitespaces in them.
I had thought of just doing something below as that should know how to deal with the format of filenames, but I can't get that to work.

for each filename in $workdir; do

It appears to give me the full file path, which will cause me issues further on in the script, due to some of the operations that expect only the filename.
Also to get the for loop to actually list the files within the directory using this method it required an * at the end. Which probably needs to be specified in the workdir variable as I couldn't get it to work by doing this in the for loop $workdir*

Anyhow, I hope that you will be able to understand my poor explaination of what I'm trying to do, and someone will be able to suggestion what would be a simple solution to this issue.
Unfortunately I can't post the script here but the operations are pretty standard so you should be able to understand what I'm trying to do.
 
Last edited:
Associate
Joined
12 Jun 2012
Posts
517
Might be worth using regex to pull the filename out of the path. Maybe something like:


# set your paths in $workdir
my $workdir='/dir/subdir/'

# remove everything up to the last / giving you just your filename
$workdir =~ s/(.*\/).*//g

# loop on the filename
for each filename in $workdir; do

the above regex should match everything up to the last / and replace it with nothing, leaving you with just your filename.

for example: if you have /var/log/httpd

the regex should find /var/log/ replace it with nothing, and leave you with httpd
The syntax might be slightly wrong, i haven't touched this properly in a while. but that should give you enough to work on.

Hope this helps
 
Associate
Joined
10 Jan 2015
Posts
10
This should work:

Code:
workdir='/dir/subdir/'

find "$workdir" -type f -maxdepth 1 | while read FILE
do
  # Make sure you quote the FILE variable
  echo "$FILE"
done
 
Back
Top Bottom