Understanding Bash

Overview

Bash (Bourne Again Shell) is the default command-line interpreter for most Linux systems. Understanding how Bash works is essential for effectively using Linux and writing shell scripts.

Basic Bash Concepts

What is a Shell?

A shell is a program that takes commands from the keyboard and gives them to the operating system to perform. Bash is one of several shell programs available.

Command Structure

command [options] [arguments]

Most commands follow this pattern:

  • command - The program to run
  • options - Flags that modify behavior (usually start with - or --)
  • arguments - Items the command acts upon
Example:
ls -la /home
Command: ls, Options: -la, Argument: /home

Echo Command

echo "Hello World"

Displays text or variables to the terminal.

Examples:
echo "Welcome to Linux"
echo $HOME (displays a variable)
echo "Today is $(date)" (command substitution)

Command History

history

Shows previously executed commands.

  • (up arrow) - Previous command
  • (down arrow) - Next command
  • !! - Repeat last command
  • !number - Repeat command by history number

Tab Completion

Press Tab to auto-complete file names, commands, and paths. Press Tab twice to see all possible completions.

Pipes and Redirection

Connect commands together to create powerful operations:

  • | (pipe) - Send output of one command to another
  • > - Redirect output to a file (overwrites)
  • >> - Append output to a file
  • < - Read input from a file
Examples:
ls -l | grep txt (find .txt files)
echo "Hello" > file.txt (write to file)
cat file.txt | wc -l (count lines)

Environment Variables

echo $VARIABLE_NAME

Variables store information that can be used by the shell and programs.

Common Variables:

  • $HOME - Your home directory
  • $PATH - Directories searched for commands
  • $USER - Your username
  • $PWD - Current directory
Setting Variables:
NAME="John"
echo $NAME
Note: No spaces around the = sign!

Command Chaining

Run multiple commands in sequence:

  • ; - Run commands sequentially
  • && - Run next command only if previous succeeds
  • || - Run next command only if previous fails
Examples:
cd /tmp ; ls (always runs both)
mkdir test && cd test (cd only if mkdir succeeds)

Important Tips

  • Case sensitive: Linux commands are case-sensitive. 'ls' works, 'LS' doesn't
  • Spaces matter: Be careful with spaces in variable assignments
  • Use quotes: Put quotes around text with spaces
  • Read error messages: They usually tell you what went wrong

Practice Levels