Bash Tips and Tricks
There are loads of tutorials on bash. This does not aim to be a reference guide instead aims to show some lesser known commands that can be super powerful if used right.
Brace expansion
With the {} symbol you can specify a brace expansion.
It can be used with number ranges and strings.
Its most useful with numbers in my opinion.
You can specify a range with ...
Examples:
1 | # Echo the integers from 1 to 100 |
Brace expansion ranges also work with letters.
1 | echo {A..z} # A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z |
You can also use brace expansion with strings.
Without the optional preamble and postscript strings, the result is just a space-separated list of the given strings.
You can add a preamble and postscript tag to generate all possible combinations.
1 | echo 1{a,b,c}2 #1a2 1b2 1c2 |
You can find more about brace expansions here.
-
You can use the - symbol to reference the last working directory.
You can use this to toggle between two directories.
1 | cd ~ |
The - basically replaces the $OLDPWD environment variable.
logger
You can send messages straight to the syslog.
If you want to debug a script which gets run from cron you can simply use logger to print a message.
1 | logger 'myscript.sh' 'im a new message' -i |
This creates an entry in /var/log/syslog on Ubuntu.
You can check it with the following command.
1 | tail /var/log/syslog |
You can add priority with the -p flag.
If you set the priority to 0 a message gets broadcasted.
You can find more info about logger here: man 1 logger
file
You can get the type of a file with the file command.
1 | file initrd.img-4.6.0-040600-generic # initrd.img-4.6.0-040600-generic: gzip compressed data |
Clipboard integration
On ubuntu you have xclip for copy pasting.
1 | sudo apt install xclip |
You can create aliases for easier use.
In ~/.bashrc
1 | alias xcopy='xclip -selection clipboard' # Copy |
Keybindings
There are loads of key combinations you can use.
Key Combination | Effect |
---|---|
ctrl + a | move the cursor to the start of the line |
ctrl + e | move the cursor to the end of the line |
ctrl + -> | jump to the start of the word on the right |
ctrl + <- | jump to the start of the word on the left |
delete | delete the next character to the right |
shift + delete | delete the next character to the left (same as backspace) |
alt + d | delete from the cursor to the end of the word to the right |
alt + backspace | delete the next word to the left |
ctrl + k | delete everything to the right from the current cursor position |
ctrl + u | delete everything to the left from the the current cursor position |
alt + . | add the argument of the last command to the end of the current command |
ctrl + y | paste the last command into the current buffer |