writing a text file in the terminal with touch

The man page for echo shows the following:

DESCRIPTION
       Echo the STRING(s) to standard output.

       -n     do not output the trailing newline

       -e     enable interpretation of backslash escapes

Which means that if you want multi-line output, you would simply start with echo -e and would add in a \n for new line.

mkdir -p ~/Desktop/new_file && echo -e "hello\nworld" >> ~/Desktop/new_file/new_file.txt

Hope this helps!


First, although your title mentions touch, the command you have actually used is mkdir so you have created a directory called new_file. You will not be able to write text to new_file as-is.

In fact there's no need to create the target file in a separate step: redirecting a command's standard output to a named file will create it automatically if it does not already exist. You can remove the (empty) new_file directory using rmdir ~/Desktop/new_file


For the reasons outlined here Why is printf better than echo? you might want to consider instead using

printf 'Hello\nworld\n' > ~/Desktop/new_file

or use a here document

cat > ~/Desktop/new_file
Hello
world

which allows you to enter multiline text directly, terminating the input with Ctrl+D when you're done.

In either case, you can replace > by >> if you want to append to, rather than overwrite the existing contents of, the file.


If I understand your question correctly you want to use:

echo "hello" > ~/Desktop/new_file.txt && echo "world" >> ~/Desktop/new_file.txt

Then to check the results use cat ~/Desktop/new_file.txt which shows:

hello
world

There's a shorter way of doing this but I'm kind of new to Linux myself.