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:
Back
Top Bottom