Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

shell

unix

echo

Is * some variable? When I do echo * it lists my working directory on one line. How can I force this command to print each item on a separate line?

like image 904
lllook Avatar asked May 11 '15 19:05

lllook


People also ask

How do you echo on different lines?

To add multiple lines to a file with echo, use the -e option and separate each line with \n. When you use the -e option, it tells echo to evaluate backslash characters such as \n for new line. If you cat the file, you will realize that each entry is added on a new line immediately after the existing content.

How do I print echo in new line?

There are a couple of different ways we can print a newline character. The most common way is to use the echo command. However, the printf command also works fine. Using the backslash character for newline “\n” is the conventional way.

How do I split a shell into multiple lines?

Using a Backslash. The backslash (\) is an escape character that instructs the shell not to interpret the next character. If the next character is a newline, the shell will read the statement as not having reached its end. This allows a statement to span multiple lines.


1 Answers

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.

like image 133
Jens Avatar answered Sep 21 '22 06:09

Jens