How do I make "echo *" print items on separate lines on Unix?
The correct way to do this is to disable non-portable entirely echo
in favor of printf
:
printf '%s\n' *
However, the printf (and echo) path has a drawback: if the command is not built-in and there are many files, the extension *
may overflow the maximum command line length (which you can query with getconf ARG_MAX
). Thus, to view the files, use the command designed to set:
ls -1
which does not have this problem; or even
find .
if you need recursive lists.
source to share
The team echo
alone cannot do this.
If you want to print each filename on its own line, I assume that you want to do something you want to do other than reading. If you tell us what it is, we can probably help you more effectively.
To list the files in the current directory, you can use ls -1
. The command ls
also prints one name per line if its output is redirected to a file or pipe.
Another alternative is the command printf
. If you give it more arguments than the format string gives it, it will cycle through the format, so this:
printf '%s\n' *
will also print one filename per line.
source to share
"*" is not a variable. It is called an extension or file name extension. bash itself expands wilcards and replaces them with filenames. Thus, * will be replaced with a list of all non-hidden items from the current directory. If you just want to print a list of items from the current directory, you can use ls. Alternatively, if you want to use echo, you can do the following:
for item in *
do
echo $item
done
it will print each item on a separate line.
You can find more details about bash globbing here: http://www.tldp.org/LDP/abs/html/globbingref.html
source to share