LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Problem with ls in a bash script (https://www.linuxquestions.org/questions/linux-newbie-8/problem-with-ls-in-a-bash-script-778880/)

dzcharles 12-30-2009 08:26 AM

Problem with ls in a bash script
 
Hi

the thing I want to do is saving the output in an array/for loop in a bash script, so I can use them later on...

The problem is that the names of the directories contains multiple words,
example: "accounting January 2010"

I've tried the following:

Code:

for i in $(ls /home/karel/accounting)
do
echo "$i"
done

i get the following output:
accounting
January
2009

as you can see every word of the directory is an entry
instead of "accounting January 2009" i get "accounting", "January" and "2009", 3 separate words

now this is the problem
someone knows a solution? so that every time the $i is called, the name of a directory is shown and not just one word...

Thx and happy new-year to you all

Dzcharles

pixellany 12-30-2009 08:37 AM

The general answer is: Don't use filenames with spaces.

This illustrates one way around the problem: (I created three files in a directory "names")

Code:

[mherring@Ath names]$ ls -l
total 0
-rw-r--r-- 1 mherring users 0 2009-12-30 06:41 one
-rw-r--r-- 1 mherring users 0 2009-12-30 06:41 third one
-rw-r--r-- 1 mherring users 0 2009-12-30 06:41 two
[mherring@Ath names]$ for fil in *; do echo $fil; done
one
third one
two
[mherring@Ath names]$ for fil in $(ls); do echo $fil; done
one
third
one
two
[mherring@Ath names]$ cd ..
[mherring@Ath play]$ for fil in names/*; do echo $fil; done
names/one
names/third one
names/two
[mherring@Ath play]$


SethsdadtheLinuxer 12-30-2009 08:42 AM

quick and dirty
cd /home/karel/accounting
for i in *
do
echo "$i"
done

schneidz 12-30-2009 08:55 AM

Quote:

Originally Posted by pixellany (Post 3808865)
The general answer is: Don't use filenames with spaces.
...

+ 1

GooseYArd 12-30-2009 09:00 AM

spaces in filenames are fine as long as you let the shell do the globbing, like Sethsdads example.

if its inconvenient to change cwd for some reason, you can also say:

for i in foo/bar/baz/*; do echo `basename $i`; done

often i'll assign the result of basename to a variable and reuse it later.

dzcharles 12-30-2009 09:03 AM

Thank you very much
this solves the problem I had :)

osor 12-30-2009 09:46 AM

Another solution is to change the field separator temporarily:
Code:

IFS='
' for i in $(ls /home/karel/accounting)


Valery Reznic 12-31-2009 02:33 AM

What about simple
Code:

ls -1 /home/karel/accounting
?


All times are GMT -5. The time now is 11:15 AM.