LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   for loop question (https://www.linuxquestions.org/questions/linux-newbie-8/for-loop-question-4175504080/)

unclesamcrazy 05-06-2014 09:45 AM

for loop question
 
I have a directory ~/test in which several sub-directories are there.
The sub-directory name has spaces and I can not rename them because the name depends on several processes.
The names are like
Code:

a 1
b 3 2

 d
 f  9

There is a for loop in a shell script, which is not running successfully because of these spaces.
Code:

#!/bin/bash
lst=$(ls ~/test)
for i in $lst; do echo "$i"; done

it prints the results
Code:

a
1
b
3
2
c
d
f
9

It is not correct, I want to use commands in "do" section of loop which needs correct directory name, now a,1,3,2... does not exist that's why the loop is giving error.
Please help

szboardstretcher 05-06-2014 10:14 AM

Just change around the field seperator.

Script:
Code:

#!/bin/bash
OLD=$IFS
IFS="\n"

lst=$(ls /home)
for i in $lst; do echo "$i"; done

IFS=$OLD

Output:
Code:

drwxr-xr-x 2 root root 4096 May  6 11:11 a 11
drwxr-xr-x 2 root root 4096 May  6 11:11 a b
drwxr-xr-x 2 root root 4096 May  6 11:11 b 1 a
[root@dev home]# bash run.sh
a 11
a b
b 1 a


suicidaleggroll 05-06-2014 10:23 AM

Use globbing directly in your for loop, don't use an intermediate variable
Code:

for i in ~/test/*; do echo $i; done
When you use an intermediate variable, the for loop splits using IFS. When you use the globbing directly in the for loop it doesn't.

DJ Shaji 05-06-2014 02:28 PM

2 people like this
 
Quote:

Originally Posted by suicidaleggroll (Post 5165696)
Code:

for i in ~/test/*; do echo $i; done

You might want to put $i in quotes, otherwise anything except echo won't find the directories:

Code:

for i in ~/test/*; do echo "$i"; done

unclesamcrazy 05-07-2014 01:21 AM

Thanks to all for your responses.

Thanks suicidaleggroll for this wonderful one line solution.

Thanks szboardstretcher, it worked for me. I could do another task because of you.
I had a list of databases which appeared when I ran ls -1, I wanted to take backup of each database but same problem was there. There were spaces in database's name. I was using mysqldump after 'do' statement but this IFS="\n" was giving little trouble, it was changing the line in the list when letter 'n' was appeared in database name so I used IFS=$'\n' and it worked for me.
Thanks again !!!


All times are GMT -5. The time now is 09:54 PM.