Essential Bash Tips and Tricks Every User Must Know

Essential Bash Tips and Tricks Every User Must Know

As a newcomer to Linux, the experience of launching a terminal can be both exhilarating and overwhelming. The terminal offers a vast array of commands and functionalities, but the sight of a blinking cursor can be intimidating for beginners. To ease this transition, we’ve compiled a selection of essential Bash tips and tricks that empower users to operate more efficiently within the terminal.

Understanding Bash Versus the Terminal

It’s essential to clarify the distinction between Bash and the terminal. The terminal serves as the interface or application through which you issue commands to interact with your operating system. In contrast, Bash is a shell—a command language interpreter for UNIX systems—that processes and executes the commands you input. Thus, when you engage with the terminal, you are essentially utilizing the Bash shell (or potentially another shell like zsh or fish).The upcoming tips and tricks primarily focus on optimizing your efficiency within the Bash environment.

1. Utilize Custom Aliases for Common Commands

Repeatedly typing lengthy commands can become cumbersome. By using aliases, you can streamline your workflow significantly. An alias allows you to assign a memorable shortcut to a longer command, reducing the amount of typing required.

For example, instead of typing git status, you can create an alias like gs. Aliases can be temporary for the session or permanent. To create a temporary alias, execute:

alias gs="git status"

Now, typing gs will execute git status. For permanent aliases, edit your Bash configuration file (typically located at “~/.bashrc” or “~/.bash_profile”) using your favorite text editor, like nano:

sudo nano ~/.bashrc

Add your alias definitions at the end of the file, save, and either restart the terminal or run:

sudo source ~/.bashrc

From now on, these aliases will be available for every session. For instance, I use the following for update commands:

alias update='sudo apt update && sudo apt upgrade -y'

This way, by simply typing update, I execute the entire command. Furthermore, with functions, you can create aliases that accept parameters:

mkcd() {mkdir -p "$1" && cd "$1"}

The command mkcd projects/new-app will create the specified directory and navigate into it. Always ensure not to overwrite existing commands to avoid confusion.

2. Instantly Search Your Command History

Scrolling through terminal history can be tedious. Fortunately, Bash provides a quick search tool making it easier to revisit previous commands.

Searching Through Command History

Simply press Ctrl + R, and your prompt will switch to allow you to start typing parts of the command you desire. As you type, Bash will display the latest matching command from your history.

You can also enhance this functionality by adding the following snippet to your “~/.inputrc” file (create it if it does not exist):

"\e[A": history-search-backward"\e[B": history-search-forwardset show-all-if-ambiguous onset completion-ignore-case on

After reloading the terminal, you’ll be able to search through your command history by typing the start of the command, followed by using the Up /Down arrow keys.

3. Chain Commands with Pipelines and Redirection

Bash enables you to link multiple commands so that the output of one is utilized as the input of another. Utilize the pipeline operator (|) for this purpose. For example, if you’re only interested in seeing Python processes among running tasks, you can combine commands as follows:

ps aux | grep python

Chaining Commands to Filter Processes

Here, ps aux lists all active processes while grep filters to display those associated with Python. You can also concatenate additional commands to form efficient scripts. For instance:

cat logfile.txt | grep "error" | wc -l

This command counts the number of lines marked as errors in a log file—three commands working in harmony.

Redirection is another crucial feature. Instead of printing command output to the terminal, you can save it to a file. For instance, to save a directory listing, you could use:

ls -l > files.txt

Use >> to append output instead of overwriting. This feature is particularly useful for logging and backing up data.

4. Run Commands in the Background

If you’ve initiated a lengthy command that occupies your terminal, you don’t have to start a new session. Instead, push the command to the background and continue using the terminal.

Press Ctrl + Z to suspend the running command and return to the shell prompt. Then, use:

bg

This resumes the command in the background. To see the status of your jobs, you can simply type:

jobs

To bring a background job back to the foreground, use:

fg %1

You can specify the job number; otherwise, fg defaults to the most recent task. If you want a command to start in the background, append & to the command:

some_long_task &

This allows the command to start without holding up your terminal. To prevent the job from terminating when the terminal closes, use:

disown -h %job

This command sends a “do not hangup” signal to that job upon shell exit. Using nohup at the start achieves a similar outcome, but be aware that background jobs might still output to your terminal.

5. Rerun the Last Command with `sudo` (sudo! !)

This particular trick addresses a common scenario: executing a command that requires superuser access. The !! command pulls the last command, allowing you to quickly rerun it with elevated privileges.

For instance, after attempting to execute an install script such as ./SCRIPT-NAME.sh and receiving a permission error, simply type:

sudo! !

Enter your password, and you’re back in action—this little command can save you considerable time and become second nature as you grow accustomed to using it.

Bash Tips And Tricks Rerun Command

6. Execute Multiple Commands at Once

To expedite tasks, Bash enables the execution of multiple commands in succession. To run commands sequentially regardless of the outcomes, utilize a semicolon (;):

mkdir newdir; cd newdir; touch file.txt

If you intend for the second command to execute only upon the first command’s success, use the double ampersand (&&):

sudo apt update && sudo apt upgrade

Conversely, if you wish for a command to run only if the preceding command fails, utilize the double vertical bars (||):

backup_database || echo "Backup failed!"

Bash allows for background processing as well; just append an ampersand to run a command in the background while freeing your terminal:

python script.py & firefox &

This executes your Python script while launching Firefox concurrently. With practice, chaining commands and managing background tasks will transform your interaction with the terminal into a more cohesive experience.

7. Discover Commands with Apropos

The apropos command is an excellent tool for locating commands based on manual entry descriptions. If you’ve used a man page, you recognize the metadata at the top. By executing apropos followed by a keyword, you can view all relevant command-line tools.

Bash Tips And Tricks Apropos

For example, typing apropos icmp retrieves a list of commands related to that topic. This feature is particularly useful for uncovering previously unfamiliar utilities, such as those for selinux; simply run apropos selinux to see available commands for managing SELinux policies.

8. Substitute Elements in the Last Command

A valuable tactic for correcting mistakes in your previous command is to use substitution. If you accidentally mistype a command, you can swiftly amend it using the caret (^) symbol.

For example, if you intend to ping maketecheasier.com but misspell it as maktecheaser.com, you could execute:

^maktecheaser.com^maketecheasier.com

This command efficiently reruns your ping request with the correct address. Such a method is particularly beneficial for lengthy commands or complex arguments. Consider using it to rectify output redirection missteps, such as replacing > with >>.

9. Pass Arguments from Previous Commands

The !$ syntax allows you to reuse the last argument from any prior command. Additionally, variations enable you to incorporate specific arguments easily.

For instance, if you’ve just edited a file using nano samplescript.sh and wish to grant it executable permissions, simply run:

chmod 755! $

You can also use ./!:2 to reference the second argument of the previous command. Here’s a quick overview of substitution options:

!^ - first argument!* - all arguments!:2-$ - second through last arguments!:2-4 - second through fourth arguments

With Bash holding a history of roughly 100 arguments, this functionality can significantly enhance your efficiency during terminal usage.

We hope these Bash tips and tricks have been insightful and will help you execute commands more effectively in the terminal. Happy Bash scripting!

Source & Images

Leave a Reply

Your email address will not be published. Required fields are marked *