Bash One-Liners
·2 mins
Table of Contents
Empty a File #
If the file does not exist, it is created. If it does exist it is truncated to zero size.
# > file.txt
MacBook-Pro:tmp kavish$ cat file.txt
not empty
MacBook-Pro:tmp kavish$
MacBook-Pro:tmp kavish$ > file.txt
MacBook-Pro:tmp kavish$
MacBook-Pro:tmp kavish$ cat file.txt
MacBook-Pro:tmp kavish$
MacBook-Pro:tmp kavish$ ls -lh file.txt
-rw-r--r-- 1 kavish wheel 0B Apr 13 15:46 file.txt
MacBook-Pro:tmp kavish$
Copy a file quickly with brace expansion #
This is my favourite. To copy a file at /etc/ssh/sshd_config
to /etc/ssh/sshd_config.bak
, you’d run:
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
Unless you change into that directory, you’d just run:
cp sshd_config sshd_config.backup
You can use brace expansion instead {...}
. The sytax is cp path{,extension}
MacBook-Pro:workshop kavish$ pwd
/tmp/workshop
MacBook-Pro:workshop kavish$
MacBook-Pro:workshop kavish$ ls /tmp/file.*
/tmp/file.txt
MacBook-Pro:workshop kavish$
MacBook-Pro:workshop kavish$ cp /tmp/file.txt{,.backup} # brace expansion
MacBook-Pro:workshop kavish$
MacBook-Pro:workshop kavish$ ls /tmp/file.*
/tmp/file.txt /tmp/file.txt.backup
MacBook-Pro:workshop kavish$
Create multiple files with brace expansion #
MacBook-Pro:workshop kavish$ echo {1..2}
1 2
MacBook-Pro:workshop kavish$ touch file{1..2}
MacBook-Pro:workshop kavish$
MacBook-Pro:workshop kavish$ ls
file1 file2
Prevent Overwriting of a file when redirecting output #
set -o noclobber
If you’re sure that you’ve to overwrite a file, you can override noclobber, by using >|
:
ls -l >| file.txt
w >| logged_in_users.txt
Last word used #
Syntax: command !$
.
MacBook-Pro:tmp kavish$ cat file.txt
hello world
MacBook-Pro:tmp kavish$
MacBook-Pro:tmp kavish$
MacBook-Pro:tmp kavish$ ls -l !$
ls -l file.txt
-rw-r--r-- 1 kavish wheel 12 Apr 14 08:48 file.txt
MacBook-Pro:tmp kavish$
Erase all shell history #
rm ~/.bash_history
Stop logging history for the current session #
unset HISTFILE
The HISTFILE
variable points to the file where the shell history should be saved.