user40647
user40647

Reputation: 65

storing output of ls command consisting of files with spaces in their names

I want to store output of ls command in my bash script in a variable and use each file name in a loop, but for example one file in the directory has name "Hello world", when I do variable=$(ls) "Hello" and "world" end up as two separate entries, and when I try to do

for i in $variable
do
  mv $i ~
done

it shows error that files "Hello" and "world" doesn't exist. Is there any way I can access all files in current directory and run some command even if the files have space(s) in their names.

Upvotes: 1

Views: 1829

Answers (2)

tckmn
tckmn

Reputation: 59283

Say it with me: don't parse the output of ls! For more information, see this post on Unix.SE.

A better way of doing this is:

for i in *
do
    mv -- "$i" ~
done

or simply

mv -- * ~

Upvotes: 2

nawK
nawK

Reputation: 741

If you must, dirfiles=(/path/of/interest/*).

And accept the admonition against parsing the output of ls!

I understand you are new to this and I'd like to help. But it isn't easy for me (us?) to provide you with an answer that would be of much help to you by the way you've stated your question.

Based on what I hear so far, you don't seem to have a basic understanding on how parameter expansions work in the shell. The following two links will be useful to you: Matching Pathnames, Parameters

Now, if your task at hand is to operate on files meeting certain criteria then find(1) will likely to do the job.

Upvotes: 2

Related Questions