DEV Community

Cover image for Bash Basics: useful commands and tools
Karim Elghamry
Karim Elghamry

Posted on

Bash Basics: useful commands and tools

Introduction

Hello fellow programmers πŸ‘‹ In this article, I will shed the light on some useful/basic bash commands and tools that might help you save time while scripting. To make it easy to follow, the article will adhere to the following format:

  • command
  • description
  • format
  • examples

Commands

1. man

  • Description: man is a useful command that displays the documentation/user manual to any command that you pass as an argument.

  • Format

$ man [COMMAND]
Enter fullscreen mode Exit fullscreen mode
  • Example

Lets try to display the manual for the echo command:

$ man echo
Enter fullscreen mode Exit fullscreen mode

the output of the previous line is:

ECHO(1)                          User Commands                         ECHO(1)                                                                                                                

NAME                                                                                                                                                                                          
       echo - display a line of text                                                                                                                                                          

SYNOPSIS                                                                                                                                                                                      
       echo [SHORT-OPTION]... [STRING]...                                                                                                                                                     
       echo LONG-OPTION                                                                                                                                                                       

DESCRIPTION                                                                                                                                                                                   
       Echo the STRING(s) to standard output.                                                                                                                                                 

       -n     do not output the trailing newline                                                                                                                                              

       -e     enable interpretation of backslash escapes                                                                                                                                      

       -E     disable interpretation of backslash escapes (default)                                                                                                                           

       --help display this help and exit                                                                                                                                                      

       --version                                                                                                                                                                              
              output version information and exit        
...                                                                                                                                     
Enter fullscreen mode Exit fullscreen mode

Notice how the man command displays the output in a formatted manner. The output usually contains the name, description and the available options/flags for the given command.

Fun fact: you can use the man command to display the manual for the man command.

man man

2. tldr

  • Description: tldr is a community driven tool that enhances the output of the man pages and displays brief and meaningful examples for the given command. This tool is not available by default, so you will have to install it first. You can visit the tool's official page to easily add it to your environment.

  • Format

$ tldr [COMMAND]
Enter fullscreen mode Exit fullscreen mode
  • Example

Lets try to display the tldr formatted docs for the echo command:

$ tldr echo
Enter fullscreen mode Exit fullscreen mode

the output of the previous line is:

echo

Print given arguments.

Print a text message. Note: quotes are optional:

    echo "{{Hello World}}"

Print a message with environment variables:

    echo "{{My path is $PATH}}"

Print a message without the trailing newline:

    echo -n "{{Hello World}}"

Append a message to the file:

    echo "{{Hello World}}" >> {{file.txt}}

Enable interpretation of backslash escapes (special characters):

    echo -e "{{Column 1\tColumn 2}}"

Enter fullscreen mode Exit fullscreen mode

Note how it gives concise examples to illustrate the usage of the given command, unlike man.

Similar to man, you can use the tldr command to display the formatted docs for tldr.

3. cat

  • Description: cat is an awesome command that lets you display files in the standard output, concatenate files together or create new files.

  • Format

$ cat [OPTION]... [FILE]...
Enter fullscreen mode Exit fullscreen mode
  • Example

Suppose that we want to print out the content of a file named example to the standard output. It can be done using:

$ cat example
Enter fullscreen mode Exit fullscreen mode

If we want to append two files, named foo and bar respectively, and save the output in a file called output:

$ cat foo bar > output
Enter fullscreen mode Exit fullscreen mode

To create a new file called new_file:

$ cat > new_file
Enter fullscreen mode Exit fullscreen mode

who doesn't like cats?
bash cat

4. grep

  • Description: grep is a powerful tool that lets you match patterns (using regex) or exact strings in a given text. It prints out the lines that contain the given pattern/string.

  • Format

$ grep [OPTION...] PATTERNS [FILE...]
Enter fullscreen mode Exit fullscreen mode
  • Example

Suppose that I have a python file called stock_analysis.py and it contains the following code:

import requests
import numpy as np
from matplotlib import pyplot as plt

eminem = requests.get("https://www.google.com/")

import pandas as pd

df = pd.read_csv('my_file.csv')
Enter fullscreen mode Exit fullscreen mode

and I want to display all the imports included in that file. We can simply use:

$ grep -F "import" stock_analysis.py
Enter fullscreen mode Exit fullscreen mode

the output of the previous command is:

import requests
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
Enter fullscreen mode Exit fullscreen mode

Suppose that instead of displaying all the imports, We want to display the aliased imports only. We can use the grep command along with regex:

$ grep  "import.*as.*" stock_analysis.py
Enter fullscreen mode Exit fullscreen mode

the output of the previous command is:

import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
Enter fullscreen mode Exit fullscreen mode

5. curl

  • Description: curl is a cli tool that lets you transfer data from/to a server over various protocols such as HTTP and FTP. curl is a massive tool that has lots of powerful features and is open source, so I encourage you to read more about it.

  • Format

$ curl [OPTION...] [URL...]
Enter fullscreen mode Exit fullscreen mode
  • Example

Suppose that I want to retrieve a random dad joke from the icanhazdadjoke API using curl. I would send a GET request and specify that I want to only accept text/plain data in the header:

$ curl -X GET https://icanhazdadjoke.com/ -H "Accept: text/plain"
Enter fullscreen mode Exit fullscreen mode

this was the joke that I've received:

Is the pool safe for diving? It deep ends.
Enter fullscreen mode Exit fullscreen mode

this API is a lot of fun and I encourage you to try your luck with it!

6. | - pipes

  • Description: |, or shall I say, pipes let you use the output of a program as an input to another program. A series of bash commands connected together using pipes is usually called a pipeline.

  • Format

$ [COMMAND1] | [COMMAND2] | ...
Enter fullscreen mode Exit fullscreen mode
  • Example

Suppose that we want to retrieve all Eminem songs that contains the word "love". We would first use curl to retrieve the list of songs from the internet, then use the output from the request as an input to the grep command to search for exact matches of the word "love":

$ curl -X GET https://pastebin.com/raw/6nfK1QRb | grep -F -i "love"
Enter fullscreen mode Exit fullscreen mode

the final filtered list of songs is:

14. Never Love Again$
14 M-bM-^@M-^T Love Game (feat. Kendrick Lamar)$
Rihanna M-bM-^@M-^S Love The Way You Lie Part II (feat. Eminem)$
09 M-bM-^@M-^S No Love (feat. Lil Wayne)$
15 M-bM-^@M-^S Love the Way You Lie (feat. Rihanna)$
17 M-bM-^@M-^S Crazy in Love$
02 M-bM-^@M-^S I Love You More$
03 M-bM-^@M-^S I Love You More (Original)$
02 M-bM-^@M-^S Love Me M-bM-^@M-^S Obie Trice, Eminem & 50 Cent$
Eminem M-bM-^@M-^S Thug Love (feat. 50 Cent & Beyonce) (Remix)$
Enter fullscreen mode Exit fullscreen mode

7. ! - bang

  • Description: !, or shall I say, bang is a useful command that lets you execute and play around with bash commands history. Combined with other characters and keywords, It can be extremely time efficient to use it instead of retyping commands from the bash history.

  • Format

$ !! # execute the last executed command
$ !* # execute the last command except for the last argument
$ !$ # get the last argument of the last executed command
$ ![PATTERN] # execute the the first command that matches the given pattern from the bash history
Enter fullscreen mode Exit fullscreen mode

8. head and tail

  • Description: head and tail are two useful bash commands that lets you display a portion of a given file. The former is used to display the first n lines of a file, and the latter is used to display the last n lines of a file. By default, n is equal to 10.

  • Format

$ head [OPTION]... [FILE]...
$ tail [OPTION]... [FILE]...
Enter fullscreen mode Exit fullscreen mode
  • Example

Dump the first and last 20 lines of a file called main.js in a file called example:

$ head --lines=20 main.js > example
$ tail --lines=20 main.js >> example
Enter fullscreen mode Exit fullscreen mode

9. fzf

  • Description: fzf is an awesome cli tool for performing fuzzy search on your files or stdout through the command line. Honestly, fzf is a really powerful tool that can do alot, but in this article, we will focus on two main usages for this tool: searching for files and search for content from the stdout. You can read more about fzf through their github page.

  • Format

$ fzf [OPTION]
Enter fullscreen mode Exit fullscreen mode
  • Example

By default, running the fzf command without any options will open an interactive searching session within the current directory. The following gif shows how we could fuzzy search for files in the current directory:

fzf

We can also pipe the stdout to fzf and search for content within the provided context:

fzf

Closing Remarks

Knowing your way around bash commands and tools can accelerate your productivity immensely. This article has covered some of the useful ones the I use on a daily basis. Feel free to mention your favorite bash commands/tools in the comments. Nevertheless, Have a great dayπŸŽ‰.

Top comments (1)

Collapse
 
tifematt profile image
Boluwatife Oladejo

Thanks for this 😊