Assuming i have a line that i want to add to a file without opening an editor.

How could i append this line

alias list='ls -cl --group-directories-first'

to this file
up vote 211 down vote accepted

You can append a line of text to a file by using the >> operator:

echo "hello world" >> my_file.txt

or in your case

echo "alias list='ls -cl --group-directories-first'" >>

Please take note of the different types of quotes.

  • 25
    I use echo myself, but be careful, if you only specify one > then the file will truncate, not append. for a safer command you can use sed: sed -i '$a hello world' filename – invert Jan 25 '11 at 8:05
  • 11
    explanation: -i will update the file (otherwise it will just print the result to stdout), $ is regex that will match the end of the file, and a appends the following text to filename. – invert Jan 25 '11 at 8:08
  • echo "hello world" >> my_file.txt does not create a new last line with HW, but add it to the string of the last line. – Timo Nov 3 '17 at 7:28
  • What is HW @timo ? – 7wp Jul 3 at 3:50
  • Maybe "Hello World" @7wp :) It's echo that adds the line break (making it a line as opposed to just a bunch of characters). You can switch off the line break at the end with -n. – Stefano Palazzo Jul 3 at 14:59

There's plenty of methods of appending to file without opening text editors, particularly via multiple available text processing utilities in Ubuntu.

  • tee -a <<< "alias list='ls -cl --group-directories-first'"
  • awk 'BEGIN{ printf "alias list=\x27ls -cl --group-directories-first\x27\n" >> "" }'
  • sed -i '$a alias list='"'"'ls -cl --group-directories-first'"'"

Adding to Stefano's answer, you can also use cat:

  • Using a heredoc:

    $ cat >> <<'EOF'
    > alias list='ls -cl --group-directories-first'
    > EOF

    <<'EOF' means "take the following as input, until you reach a line that is just EOF". The quotes mean to take the input literally.

  • Or inputting the line on stdin:

    $ cat >>

    Then paste or type in the line, press Enter to go to a new line, then press Ctrl+D to mark the end.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.