How to force "echo *" to print items on separate lines in Unix?

The correct way to do this is to ditch the non-portable echo completely in favor of printf:

 printf '%s\n' *

However, the printf (and echo) way have a drawback: if the command is not a built-in and there are a lot of files, expanding * may overflow the maximum length of a command line (which you can query with getconf ARG_MAX). Thus, to list files, use the command that was designed for the job:

ls -1

which doesn't have this problem; or even

find .

if you need recursive lists.


The echo command by itself cannot do this.

If you want to print each file name on its own line, I guess there's something you want to do with the output other than just reading it. If you tell us what that is, we can probably help you more effectively.

To list the files in the current directory, you can use ls -1. The ls command also prints one name per line if its output is redirected to a file or through a pipe.

Another alternative is the printf command. If you give it more arguments than are specified in the format string, it will cycle through the format, so this:

printf '%s\n' *

will also print one file name per line.


* - is not a variable. It's called globbing or filename expansion - bash itself expands wildcards and replaces them with filenames. So * will be replaced with list of all non-hidden items from current directory.

If you just want to print the list of files in the current directory - you can use ls. Also, if you wish to use echo - you can do it like this:

for item in *
do
    echo $item
done

it will print each item on a separate line.

More details about bash globbing you can find here: http://www.tldp.org/LDP/abs/html/globbingref.html

Tags:

Unix

Shell

Echo