Bash Scripting Tips

December 24, 2024

Alina Orel

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/