Bash (Bourne Again Shell) is a powerful tool, and many users are unaware of the lesser-known features that can save time and make scripting more efficient. In this article, we explore unique Bash tricks to level up your command-line game. Open your terminal and type along as you discover these gems.
๐ Brace Expansion for Quick File Creation
Brace expansion can save you from repetitive typing. Use it to create multiple files or directories in a single command.
This creates the directories project/src
, project/bin
, and project/docs
in one go. You can also use it to generate files:
This command creates file1.txt
, file2.txt
, and so on up to file5.txt
.
๐ Substring Extraction in Variables
Easily manipulate strings stored in variables using Bashโs substring capabilities.
This extracts Bash
from the variable, starting at position 6 (0-indexed) and taking 4 characters.
๐ Reverse a File’s Content
Want to reverse the lines in a file? The tac
command does this elegantly:
If you want to reverse the characters of each line as well:
๐ Quick Arithmetic with Bash
Perform simple arithmetic directly in your terminal using double parentheses:
Bash supports basic operators like addition, subtraction, multiplication, division, and modulus.
๐ Run Commands Until Success
The until
loop is handy for retrying commands until they succeed:
This example keeps pinging Google until the connection is successful.
๐ Create Temporary Files Safely
Avoid overwriting files with the mktemp
command:
This ensures a unique temporary file is created securely.
๐ Search Command History Quickly
Press Ctrl + r
and start typing a command to search your command history interactively. Once you find the desired command, press Enter to execute it, or use the arrow keys to edit it.
๐ Run Commands in Parallel
Speed up tasks by running commands in parallel using &
:
For example:
This runs both ls
and pwd
simultaneously.
๐ Print a Sequence of Numbers
Generate number sequences without external tools like seq
:
You can also customize the increment:
๐ Check Script Syntax Without Running It
Validate your Bash scriptโs syntax before execution using the -n
flag:
If thereโs a syntax error, Bash will report it without executing the script.
๐ Redirect Output and Error Streams Separately
Separate standard output (stdout) and error (stderr) streams in a single command:
To combine them into one file:
๐ Nullify Command Output
Silence command output entirely by redirecting it to /dev/null
:
This is especially useful for scripts where you want to suppress unwanted messages.
These tricks barely scratch the surface of what Bash can do, but they demonstrate its flexibility and power. Experiment with these commands and incorporate them into your daily workflow to boost efficiency. Got a favorite Bash trick? Share it in the comments below!
Happy coding https://synpass.pro/contactsynpass/