Useful-One-Liners Flashcards

how to get various tasks done with just bash built-in commands and bash programming language constructs

1
Q

Empty a file (truncate to 0 size)

A

$ > 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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Append a string to a file

A

$ echo “foo bar baz”&raquo_space; file

This one-liner uses a different output redirection operator&raquo_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”&raquo_space; file

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Read the first line from a file and put it in a variable

A

$ read -r line < file

This one-liner uses the built-in bash command read and the input redirection operator

How well did you know this?
1
Not at all
2
3
4
5
Perfectly