Bash is a powerful command-line shell that can be used to perform a wide range of tasks, from managing files and directories to automating system administration. By learning a few simple tips and tricks, you can significantly boost your productivity and efficiency when using Bash.
Here are a few of my favorite Bash tips and tricks, in a randomized order:
- Use Ctrl+R to search your command history as you type. This is a great way to quickly find and reuse previous commands.
shopt -s cdspellto automatically fix your
cd folderspelling mistakes. This can save you a lot of time and frustration, especially if you are working with directories with long or complex names.
!!:nto select the nth argument of the last command, and !$ to select the last argument. For example,
ls file1 file2 file3; cat !!:1-2will show all files and then cat only the first two files.
- Input from the command line as if it were a file by replacing
command < file.inwith
command <<< "some input text". This can be useful for piping input into commands or for providing input to scripts.
- Use the ^ (caret) operator to replace characters from the last command. For example,
ls docs; ^docs^webis equal to
ls web. The second argument can be empty.
- Use !! to expand to the last typed command. This is useful for root commands that require sudo privileges. For example, if you type
cat /etc/...and get a permission denied error, you can simply type
sudo !!to retry the command with sudo privileges.
- Use traps for cleaning up Bash scripts on exit. This is especially important for scripts that perform destructive operations, such as deleting files or modifying system settings.
nohup ./long_script &to leave stuff running in the background even if you logout. This is useful for long-running tasks such as backups or data processing jobs.
shopt -s histverify histreeditin your ~/.bashrc to double-check all expansions before submitting a command. This can help to prevent errors from typos or unexpected expansions.
- Use Esc-. to fetch the last parameter of the previous command. This can be useful for quickly reusing parameters in complex commands.
- Use Ctrl+X Ctrl+E to open an editor to work with long or complex command lines. This can be useful for debugging commands or for testing different options.