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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With