Bash cheat sheet: Top 25 commands and creating custom commands

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

Bash Cheat Sheet: Top 25 Commands & Creating Custom Commands

Bash (Bourne Again SHell) is a powerful command-line interface used in Unix/Linux environments. Whether you're a beginner or an experienced user, having a handy reference for commonly used commands and methods to create custom commands can significantly enhance your productivity. This cheat sheet covers the Top 25 Bash Commands along with Creating Custom Commands.

Top 25 Bash Commands

1. 'ls' – List Directory Contents

Displays files and directories within the current directory.

Usage:

ls

Common Options:

  • -l : Long listing format
  • -a : Include hidden files
  • -h : Human-readable file sizes

Example:

ls -lah

2. 'cd' – Change Directory

Navigates between directories.

Usage:

cd [directory]

Examples:

cd /home/user/Documents cd .. cd ~ # Home directory

3. 'pwd' – Print Working Directory

Displays the current directory path.

Usage:

pwd

Example:

/home/user/Documents

4. 'cp' – Copy Files and Directories

Copies files or directories from one location to another.

Usage:

cp [options] source destination

Common Options:

  • -r : Recursive copy (for directories)
  • -i : Interactive (prompt before overwrite)
  • -v : Verbose (detailed output)

Examples:

cp file.txt /backup/ cp -r /source_dir /backup_dir

5. 'mv' – Move or Rename Files and Directories

Moves or renames files and directories.

Usage:

mv [options] source destination

Common Options:

  • -i : Interactive
  • -v : Verbose

Examples:

mv oldname.txt newname.txt mv /file.txt /new_directory/

6. 'rm' – Remove Files or Directories

Deletes files or directories.

Usage:

rm [options] file

Common Options:

  • -r : Recursive (for directories)
  • -f : Force deletion
  • -i : Interactive

Examples:

rm file.txt rm -rf /unwanted_directory

⚠️ Caution: rm -rf permanently deletes files/directories without confirmation.


7. 'mkdir' – Make Directories

Creates new directories.

Usage:

mkdir [options] directory_name

Common Options:

  • -p : Create parent directories as needed

Examples:

mkdir new_folder mkdir -p parent_folder/child_folder

8. 'rmdir' – Remove Empty Directories

Deletes empty directories.

Usage:

rmdir directory_name

Example:

rmdir empty_folder

9. 'touch' – Create or Update File Timestamps

Creates empty files or updates the timestamps of existing files.

Usage:

touch filename

Examples:

touch newfile.txt touch existingfile.txt

10. 'echo' – Display Messages or Variables

Prints text or variable values to the terminal.

Usage:

echo [options] string

Common Options:

  • -e : Enable interpretation of backslash escapes

Examples:

echo "Hello, World!" echo $HOME echo -e "Line1\nLine2"

11. 'cat' – Concatenate and Display Files

Displays the contents of files, concatenates multiple files, or creates new files.

Usage:

cat [options] file

Common Options:

  • -n : Number all output lines

Examples:

cat file.txt cat file1.txt file2.txt > combined.txt

12. 'less' – View File Contents Page by Page

Allows browsing through large files interactively.

Usage:

less filename

Example:

less /var/log/syslog

Navigation:

  • Space : Next page
  • b : Previous page
  • /search : Search text
  • q : Quit

Searches for patterns within files or input.

Usage:

grep [options] pattern [file]

Common Options:

  • -i : Ignore case
  • -r : Recursive search
  • -n : Show line numbers

Examples:

grep "error" logfile.txt grep -i "warning" *.log grep -rn "TODO" /path/to/code/

Searches for files and directories based on various criteria.

Usage:

find [path] [options] [expression]

Common Examples:

  • Find files by name:
    find /home/user -name "file.txt"
  • Find directories:
    find /var -type d -name "log"
  • Find and delete files:
    find /tmp -type f -name "*.tmp" -delete

15. 'chmod' – Change File Permissions

Modifies the permissions of files or directories.

Usage:

chmod [options] mode file

Examples:

  • Add execute permission:
    chmod +x script.sh
  • Set permissions using numeric notation:
    chmod 755 program

16. 'chown' – Change File Owner and Group

Changes the ownership of files or directories.

Usage:

chown [options] user[:group] file

Examples:

chown user:group file.txt chown -R user:group /path/to/directory

17. 'tar' – Archive and Extract Files

Creates and extracts compressed archives.

Usage:

tar [options] archive.tar [files]

Common Options:

  • -c : Create archive
  • -x : Extract archive
  • -v : Verbose
  • -f : Specify filename
  • -z : Compress with gzip
  • -j : Compress with bzip2

Examples:

  • Create a tar.gz archive:
    tar -czvf archive.tar.gz /path/to/directory
  • Extract a tar.gz archive:
    tar -xzvf archive.tar.gz

18. 'zip' & 'unzip' – Compress and Decompress Files

Compresses and decompresses ZIP archives.

Usage:

zip [options] archive.zip files unzip [options] archive.zip

Common Options:

  • -r : Recursive (for directories)
  • -d : Extract to a specific directory

Examples:

zip -r archive.zip /path/to/directory unzip archive.zip -d /extracted/path/

19. 'wget' – Download Files from the Web

Non-interactive network downloader.

Usage:

wget [options] URL

Common Options:

  • -O : Specify output filename
  • -c : Continue partially downloaded files
  • -r : Recursive download

Examples:

wget https://example.com/file.zip wget -O custom_name.zip https://example.com/file.zip

20. 'curl' – Transfer Data with URLs

Transfers data from or to a server using various protocols.

Usage:

curl [options] URL

Common Options:

  • -O : Write output to a file named as the remote file
  • -o : Specify output filename
  • -L : Follow redirects
  • -I : Fetch headers only

Examples:

curl -O https://example.com/file.zip curl -o localfile.html https://example.com curl -I https://example.com

21. 'ssh' – Secure Shell for Remote Login

Connects to remote machines securely.

Usage:

ssh [options] user@hostname

Common Options:

  • -p : Specify port
  • -i : Specify identity file (private key)

Examples:

ssh user@192.168.1.10 ssh -p 2222 user@server.com

22. 'scp' – Secure Copy Files Between Hosts

Copies files securely between local and remote systems.

Usage:

scp [options] source destination

Common Options:

  • -r : Recursive copy
  • -P : Specify port

Examples:

  • Copy local file to remote:
    scp file.txt user@remote:/path/to/destination/
  • Copy remote file to local:
    scp user@remote:/path/to/file.txt /local/destination/

23. 'sudo' – Execute Commands with Superuser Privileges

Runs commands with elevated (superuser) privileges.

Usage:

sudo command

Example:

sudo apt update sudo rm /protected/file.txt

Note: Use sudo with caution as it grants powerful permissions.


24. 'ps' – Display Current Processes

Shows currently running processes.

Usage:

ps [options]

Common Options:

  • -e : Show all processes
  • -f : Full-format listing
  • -u : Specify user

Examples:

ps -ef ps -u username

25. 'kill' – Terminate Processes

Sends signals to terminate or manage processes.

Usage:

kill [options] PID

Common Signals:

  • -SIGTERM (15) : Graceful termination
  • -SIGKILL (9) : Force termination

Examples:

kill 1234 # Sends SIGTERM to PID 1234 kill -9 1234 # Sends SIGKILL to PID 1234 kill $(pidof process) # Kills all instances of 'process'

Tip: Use pkill or killall for killing processes by name.


Creating Custom Commands

Custom commands in Bash can streamline your workflow by automating repetitive tasks or simplifying complex commands. You can create custom commands using aliases, shell functions, or shell scripts.

1. Aliases

Aliases are shortcuts for longer commands. They are best suited for simple command substitutions.

Creating an Alias:

alias shortname='long_command'

Examples:

  • Update system packages (Ubuntu/Debian):
    alias update='sudo apt update && sudo apt upgrade'
  • List with human-readable sizes:
    alias ll='ls -lah'

Making Aliases Persistent: Add your aliases to the ~/.bashrc or ~/.bash_profile file.

Example:

echo "alias ll='ls -lah'" >> ~/.bashrc source ~/.bashrc

2. Shell Functions

Shell functions are more powerful than aliases and can handle more complex tasks, including accepting arguments.

Creating a Function:

function_name() { commands }

Examples:

  • Create a directory and navigate into it:

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

    Usage:

    mkcd new_folder
  • Backup a file:

    backup() { cp "$1" "$1.bak" echo "Backup of $1 created as $1.bak" }

    Usage:

    backup important.txt

Making Functions Persistent: Add your functions to the ~/.bashrc or ~/.bash_profile file.

Example:

echo "mkcd() { mkdir -p \"\$1\" && cd \"\$1\"; }" >> ~/.bashrc source ~/.bashrc

3. Shell Scripts

Shell scripts are executable files containing a series of commands. They are ideal for automating complex or multi-step tasks.

Creating a Shell Script:

  1. Create the script file:

    touch myscript.sh
  2. Add a shebang and commands:

    #!/bin/bash echo "Hello, World!"
  3. Make the script executable:

    chmod +x myscript.sh
  4. Run the script:

    ./myscript.sh

Example: Backup Script

#!/bin/bash # Backup directory BACKUP_DIR="$HOME/backups" # Create backup directory if it doesn't exist mkdir -p "$BACKUP_DIR" # Current date DATE=$(date +%Y-%m-%d) # Backup files tar -czvf "$BACKUP_DIR/backup-$DATE.tar.gz" /path/to/important/files echo "Backup completed: backup-$DATE.tar.gz"

Usage:

./backup.sh

Storing Scripts in PATH: To use your scripts as commands from anywhere:

  1. Move the script to a directory in your PATH, such as /usr/local/bin or create a ~/bin directory.

    mkdir -p ~/bin mv myscript.sh ~/bin/myscript chmod +x ~/bin/myscript
  2. Ensure ~/bin is in your PATH by adding the following to your ~/.bashrc:

    export PATH="$HOME/bin:$PATH"
  3. Reload your ~/.bashrc:

    source ~/.bashrc
  4. Run your custom command:

    myscript

4. Adding Custom Commands to PATH

By placing your custom scripts or binaries in directories included in your PATH environment variable, you can execute them from anywhere without specifying their full path.

Steps:

  1. Choose or create a directory for your custom commands, e.g., ~/bin.

    mkdir -p ~/bin
  2. Add the directory to your PATH by editing ~/.bashrc or ~/.bash_profile:

    echo 'export PATH="$HOME/bin:$PATH"' >> ~/.bashrc source ~/.bashrc
  3. Move your scripts to this directory and ensure they are executable.

    mv myscript.sh ~/bin/myscript chmod +x ~/bin/myscript
  4. Use your custom commands from anywhere:

    myscript

Tips & Best Practices

  • Organize Your Custom Scripts: Keep your scripts in a dedicated directory (e.g., ~/bin) to maintain organization.

  • Use Descriptive Names: Name your aliases, functions, and scripts clearly to reflect their functionality.

  • Backup Configuration Files: Before making significant changes to ~/.bashrc or ~/.bash_profile, back them up.

    cp ~/.bashrc ~/.bashrc.backup
  • Reload Shell Configuration: After updating ~/.bashrc or ~/.bash_profile, apply changes immediately.

    source ~/.bashrc
  • Leverage Tab Completion: Bash's tab completion can speed up command entry. For custom scripts, ensure they don't conflict with existing commands.

  • Document Your Custom Commands: Add comments to your functions and scripts to explain their purpose and usage.

  • Use Version Control: Consider storing your custom scripts in a Git repository to track changes and collaborate.

Additional Resources

By mastering these top Bash commands and learning how to create custom commands, you can significantly improve your efficiency and effectiveness in the command-line environment. Whether you're managing files, automating tasks, or configuring your shell, this cheat sheet serves as a valuable reference to enhance your Bash proficiency.

TAGS
Coding Interview
System Design Interview
CONTRIBUTOR
Design Gurus Team

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
How do you compare float and double while accounting for precision loss in C++?
How to crack system design interview at Amazon?
How to crack system design interview at Amazon?
What is the ByteDance interview process?
What is the ByteDance process?
Related Courses
Image
Grokking the Coding Interview: Patterns for Coding Questions
Image
Grokking Data Structures & Algorithms for Coding Interviews
Image
Grokking Advanced Coding Patterns for Interviews
Image
One-Stop Portal For Tech Interviews.
Copyright © 2024 Designgurus, Inc. All rights reserved.