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

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.


"*" - is not a variable. It's called globbing or filename expansion - bash itself expands wilcards and replace 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 items from current dir - you can use ls. Also, if you wish to use "echo" - you can do like this:

for item in *do    echo $itemdone

it will print each item on separate line.

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


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.