Useful-One-Liners Flashcards
how to get various tasks done with just bash built-in commands and bash programming language constructs
Empty a file (truncate to 0 size)
$ > file
This one-liner uses the output redirection operator >. Redirection of output causes the file to be opened for writing. If the file does not exist it is created; if it does exist it is truncated to zero size. As we’re not redirecting anything to the file it remains empty.
If you wish to replace the contents of a file with some string or create a file with specific content, you can do this:
$ echo “some string” > file
Append a string to a file
$ echo “foo bar baz”»_space; file
This one-liner uses a different output redirection operator»_space;, which appends to the file. If the file does not exist it is created. The string appended to the file is followed by a newline. If you don’t want a newline appended after the string, add the -n argument to echo:
$ echo -n “foo bar baz”»_space; file
Read the first line from a file and put it in a variable
$ read -r line < file
This one-liner uses the built-in bash command read and the input redirection operator