-1

How to retrieve all names from one directory?

The directory contains names such as :

.foo bar
.10
10.foo bar
foo bar.foo bar

I tried

for item in $(ls "/opt/$PATH")
do
    echo "$item"
done

Will anyone advise? Thank you.

dev.bev
  • 13
  • 1
  • 1
    See also [Why you don't parse the output of `ls`](http://mywiki.wooledge.org/ParsingLs), and [BashPitfalls #1](http://mywiki.wooledge.org/BashPitfalls#for_i_in_.24.28ls_.2A.mp3.29). – Charles Duffy Mar 16 '18 at 23:04

1 Answers1

5

Don't parse the output of ls. Use globs, for example:

for item in "/opt/$path"/*; do echo "$item"; done

If you want just the filename without absolutely path, you have several options, for example:

for item in "/opt/$path"/*; do basename "$item"; done

or:

(cd "/opt/$path" && for item in *; do echo "$item"; done)

If you want to include hidden files too, you can set dotglob option before the above commands:

shopt -s dotglob

As a side note, the use of "/opt/$PATH" is extremely suspicious. PATH is an extremely important variable in the shell, containing a colon-separated list of directories in which the shell looks for commands. It's unlikely that "/opt/$PATH" will have the effect that you want. Do not use this variable for other purposes than it's designed.

janos
  • 120,954
  • 29
  • 226
  • 236