Using the Bash Shell on Ubuntu

The Bash shell is your indispensable command-line companion. This guide will walk you through everything you need to know to become proficient with Bash. We’ll cover everything from basic navigation to powerful scripting techniques.

1. What Is the Shell, Anyway? (Understanding the Basics)

The shell is your primary interface for interacting with the Ubuntu operating system. Think of it as a command interpreter: you type commands, and the shell interprets them and tells the operating system what to do. It’s a text-based environment, which might seem old-school, but it’s incredibly powerful and efficient. The default shell on Ubuntu is Bash (Bourne Again SHell), an enhanced version of the original Bourne shell.

Why use the shell instead of the graphical interface?

  • Automation: You can write scripts to automate repetitive tasks.
  • Power and Flexibility: Many system administration tasks are easier and faster to perform in the shell.
  • Remote Access: When you connect to a remote server (often via SSH), you’ll typically be working in a shell environment.
  • Troubleshooting: The shell gives you low-level access to the system, which is essential for diagnosing problems.
  • Resource Efficiency: The shell uses far fewer system resources than a graphical desktop environment.

Read: How to install GNOME Shell Extensions in Ubuntu

2. Getting to the Shell: Your Command-Line Starting Point

There are several ways to access the Bash shell on Ubuntu:

  • Terminal Window (GNOME Desktop): If you’re running the GNOME desktop environment, you can open a terminal window. Look for an application called “Terminal” or “Console”. You can usually find it by searching in the Activities overview.
  • Keyboard Shortcut: The Ctrl+Alt+T shortcut is a quick way to open a terminal window in most Ubuntu desktop environments.
  • Remote Login (SSH): If you’re connecting to a remote Ubuntu server, you’ll typically use SSH (Secure Shell). This gives you a shell prompt on the remote machine.
  • Virtual Consoles: Ubuntu provides multiple virtual consoles (text-mode sessions). You can access them using Ctrl+Alt+F1 through Ctrl+Alt+F6. (Ctrl+Alt+F7 usually returns you to the graphical desktop.)

Why use the shell instead of the graphical interface

3. Typing Commands: The Basics of Bash Interaction

Once you have a shell prompt (which usually looks like username@hostname:~$ or root@hostname:~#), you can start typing commands.

  • Basic Syntax: Most commands follow the format: command [options] [arguments]
    • command: The name of the program you want to run.
    • options: Flags that modify the behavior of the command (often start with - or --).
    • arguments: The input data the command will work on (e.g., filenames, directory names).
  • Case Sensitivity: Linux commands and filenames are case-sensitive. ls is different from LS.
  • Execution: After typing a command, press the Enter key to execute it.

Example:

ls -l /home/demo

This command lists the contents of the /home/demo directory (ls) in long format (-l).

4. Finding Help: Getting Information About Commands

There are thousands of commands available on a typical Ubuntu system, and it’s impossible to remember them all. Fortunately, there are built-in tools to help you.

  • man (Manual Pages): The man command displays the manual page for a command. This is the most comprehensive source of information.
    man ls
    

    This will show you the manual page for the ls command, including all its options and arguments. Use the arrow keys or Page Up/Page Down to navigate, and press q to quit.

  • --help: Many commands support a --help option (or sometimes -h) that provides a brief summary of usage.
    ls --help
    
  • apropos: Search the manual page names and descriptions.
    apropos copy
    
  • whatis: It displays one-line manual page descriptions.
    whatis ls
    

5. Editing Commands: Bash Shortcuts for Efficiency

Bash provides a number of shortcuts to make editing commands at the prompt easier. These can save you a lot of time and frustration.

  • Arrow Keys: Move the cursor left and right, and scroll through the command history (up/down).
  • Ctrl+A: Move the cursor to the beginning of the line.
  • Ctrl+E: Move the cursor to the end of the line.
  • Ctrl+U: Delete from the cursor to the beginning of the line.
  • Ctrl+K: Delete from the cursor to the end of the line.
  • Ctrl+W: Delete the word before the cursor.
  • Alt+D or Esc then d: Delete the word after the cursor.
  • Ctrl+Y: Paste (yank) the last deleted text.
  • Ctrl+L: Clear the screen (the current command remains at the top).
  • Ctrl+R: Start a search through your history.
  • Ctrl+_: Undo.

Personal Insight: Mastering these shortcuts is a huge productivity booster. I use Ctrl+A, Ctrl+E, Ctrl+U, and Ctrl+K constantly.

Read: Linux Bash usage tips

6. Command History: Your Bash Shell’s Memory

Bash keeps a record of the commands you’ve typed. This is incredibly useful for repeating commands, correcting mistakes, and remembering what you did earlier.

  • Up/Down Arrow Keys: Scroll through the command history.
  • history command: Displays the entire command history (up to a limit, usually 500 or 1000 commands).
    history
    
  • !n: Execute command number n from the history. For example, !123 would run the command numbered 123 in your history.
  • !!: Execute the previous command.
  • !string: Execute the most recent command that starts with string. For example, !ls would run the most recent ls command.
  • Ctrl+R: Reverse-i-search. Start typing, and Bash will search backward through your history for matching commands. Press Ctrl+R repeatedly to cycle through matches. Press Enter to execute the found command, or Ctrl+G to cancel.

Personal Insight: Ctrl+R (reverse-i-search) is one of the most efficient features for finding and re-running commands.

7. Filename Shortcuts: Working with Multiple Files

Bash provides “wildcards” to make it easier to work with multiple files at once.

  • *: Matches zero or more characters. *.txt matches all files ending in .txt. report* matches report, report1, report2023, etc.
  • ?: Matches exactly one character. file?.txt matches file1.txt, fileA.txt, but not file10.txt.
  • [ ]: Matches any one of the characters inside the brackets. file[123].txt matches file1.txt, file2.txt, and file3.txt. You can also use ranges: file[a-z].txt matches filea.txt, fileb.txt, …, filez.txt.
  • [! ]: Matches any character that is not mentioned between brackets.
  • { }: Bash will create all possible combinations within this block.

Examples:

ls *.txt          # List all .txt files
cp report?.doc backup/  # Copy report1.doc, report2.doc, etc. to backup/
rm file[1-5].txt   # Remove file1.txt, file2.txt, ..., file5.txt
mkdir {monday,tuesday,wednesday,thursday,friday,saturday,sunday}
# Creates 7 directories with days names.

8. Filename and Path Completion: Let Bash Do the Typing

Bash can automatically complete filenames and paths for you. This is a huge time-saver and helps prevent typos.

  • Tab Key: Press the Tab key after typing the first few characters of a filename or path. Bash will try to complete it. If there’s only one match, it will complete the entire name. If there are multiple matches, pressing Tab twice will show you a list of possibilities.

Example:

  1. Type ls /usr/lo
  2. Press Tab. Bash might complete it to ls /usr/local/.
  3. Type b and press Tab again. Bash might complete it to ls /usr/local/bin/.

9. Input and Output Redirection: Controlling Data Flow

Bash provides powerful mechanisms for controlling how data flows between commands and files:

  • > (Redirect stdout): Sends the output of a command to a file, overwriting the file if it exists.
  • >> (Append stdout): Adds the output of a command to the end of a file.
  • < (Redirect stdin): Takes input for a command from a file.
  • 2> (Redirect stderr): Sends error messages to a file.
  • &> (Redirect stdout and stderr): Sends both standard output and error messages to the same file.
  • 2>&1: Redirects stderr to stdout.
  • /dev/null: A special file that discards any data written to it.

Real-world scenario: Logging system checks while discarding errors:

# Log successful directory listings but discard errors
ls -la /home/users/ > user_directories.log 2>/dev/null

10. Connecting Commands with Pipes: The Power of |

Pipes, represented by the | character, allow you to chain commands together. The stdout of the first command becomes the stdin of the second command.

Example:

ps -ef | grep myprogram

This command lists all processes (ps -ef) and then pipes that output to the grep command, which filters the output, showing only lines that contain “myprogram”.

You can chain multiple commands together with pipes:

ls -l | sort -r | head -n 5

This lists files, sorts them in reverse order (sort -r), and then displays the first 5 lines (head -n 5).

11. Creating Command Shortcuts: Bash Aliases

Aliases are shortcuts for commands. You can define your own aliases to save typing.

  • alias command: Used to create and view aliases.

Example:

alias l='ls -l'

Now, typing l will be equivalent to typing ls -l.

  • To make aliases permanent: Add the alias commands to your ~/.bashrc file. This file is executed every time you start a new interactive, non-login shell.
  • To remove an alias: Use the unalias command followed by the alias name.
unalias l

12. Environment Variables: Customizing Your Shell

Environment variables are variables that store information about your shell environment. They can affect how commands behave.

  • env command: Displays a list of current environment variables.
  • echo $VARIABLE_NAME: Displays the value of a specific variable. For example, echo $HOME will show your home directory.
  • export VARIABLE_NAME=value: Sets or modifies an environment variable. For example:
    export EDITOR=nano
    

    This sets the EDITOR variable to nano, which many programs use to determine the default text editor.

  • PATH variable: This is a crucial variable. It’s a colon-separated list of directories where the shell searches for executable commands. If you put your own scripts in a directory, you might need to add that directory to your PATH.
    export PATH=$PATH:/home/myuser/bin
    

    This appends /home/myuser/bin to the existing PATH.

13. Writing Bash Scripts: Automating Your Tasks

A shell script is a powerful way to automate sequences of commands:

  • A shell script is a text file containing a sequence of Bash commands.
  • The first line is usually #!/bin/bash (the shebang), which tells the system to use the Bash interpreter.
  • Make the script executable with chmod +x scriptname.sh.
  • Run the script with ./scriptname.sh (if it’s in the current directory) or by specifying the full path.
  • Use bash scriptname.sh as an alternative to run the script.
  • Scripts can use variables, loops, conditional statements, and other programming constructs.

Simple script example:

#!/bin/bash
# This script backs up important directories to a specified location

BACKUP_DIR="/mnt/backup/$(date +%Y-%m-%d)"
DIRS_TO_BACKUP=("/home/user/documents" "/var/www" "/etc")

# Create backup directory
mkdir -p "$BACKUP_DIR"

# Backup each directory
for dir in "${DIRS_TO_BACKUP[@]}"; do
    echo "Backing up $dir..."
    cp -r "$dir" "$BACKUP_DIR"
done

echo "Backup completed at $(date)"

14. Summary: Putting It All Together

The Bash shell is a powerful tool for interacting with your Ubuntu system. This guide has covered the essential concepts:

  • Understanding the shell and accessing it.
  • Entering commands and getting help.
  • Command-line editing and history.
  • Filename shorthand and completion.
  • Input/output redirection and pipes.
  • Configuring aliases and environment variables.
  • Writing basic shell scripts.

Mastering these skills will significantly improve your efficiency and productivity as an Ubuntu administrator.

FAQ

  1. Q: What’s the difference between a shell and a terminal?A: A terminal is a text-based window that provides access to a shell. The shell is the command interpreter that runs inside the terminal.
  2. Q: Can I use a different shell than Bash?A: Yes! Ubuntu (and Linux in general) supports many different shells, such as zsh, fish, ksh, and tcsh. You can change your default shell using the chsh command. However, Bash is the most common and widely used shell.
  3. Q: How do I execute commands from a file without making it executable?A: You can source the file instead. By typing source file_name or . file_name. This is useful if you only want to add functions or variables to your current session.
  4. Q: I made changes to my ~/.bashrc file, but they don’t seem to be taking effect.A: The ~/.bashrc file is read when you start a new interactive, non-login shell. To apply the changes to your current shell, you can either:
    • Open a new terminal window.
    • Run source ~/.bashrc (or the shorthand . ~/.bashrc). This re-reads the file in the current shell.
  5. Q: How can I learn the location on the file system of a specific command?A: Use the which command.
    which ls
    
  6. Q: How can I know if a command is a built-in or not?A: Use the type command.
    type cd
    type ls
    
  7. Q: How do I list all available options and arguments of a command?A: Using the man command, it will display the user manual of any command that you can run on the terminal.
    man command_name
    
  8. Q: I need to search for commands, what should I do?A: You can use the apropos command, it searches the manual page names and descriptions.
    apropos keyword
    
  9. Q: How can I find and execute a command that I ran previously?A: You can use the Up/Down arrows, or even use the history command.
  10. Q: What are wildcards, and how can I use them in Bash?A: Wildcards are special characters that represent one or more characters in filenames, allowing you to work with multiple files at once.
    • *: Matches zero or more characters.
    • ?: Matches exactly one character.
    • []: Matches any one of the characters inside the brackets.
    • [! ]: Matches any character that is not mentioned between brackets.
    • { }: Bash will create all possible combinations within this block.
  11. Q: How can I quickly complete a filename or path while typing a command?A: Use the Tab key for filename and path completion. Press Tab after typing the first few characters, and Bash will try to complete the name.
  12. Q: I have a long list of commands I need to run repeatedly. How can I avoid typing them every time?A: Create a Bash script! A shell script is a text file containing a sequence of commands. You can then run the script instead of typing each command individually.
  13. Q: What’s the purpose of the #!/bin/bash line at the beginning of a script?A: This line, called the “shebang,” tells the operating system which interpreter to use to run the script. #!/bin/bash specifies the Bash shell interpreter.
  14. Q: Why do I need to use ./ to run a script in my current directory?A: For security reasons, the current directory (.) is usually not included in the system’s PATH variable (which lists the directories where the shell searches for commands). The ./ explicitly tells the shell to look for the script in the current directory.
  15. Q: How do I know what my current shell is set to?A: Type the following:
    echo $0
    

If you like the content, we would appreciate your support by buying us a coffee. Thank you so much for your visit and support.

 

Nikolaus Oosterhof

Nikolaus holds a degree in software development and has a strong passion for all things tech-related, especially gadgets with screens. Though he is nostalgic for older phone models, he's a retired gamer and continues to enjoy programming in open-source environments. Additionally, Nikolaus enjoys writing about Linux, macOS and Windows and has experience designing web pages.

Leave a Reply