Skip to content

Shell

The shell is a command-line interface that allows you to interact with your operating system through text commands. It provides powerful tools for file management, process control, and automation, making it an essential skill for developers and system administrators.

Basic Commands

# List files and directories
ls                  # Basic listing
ls -la             # Detailed listing including hidden files
ls -lh             # Human-readable file sizes

# Change directory
cd /path/to/directory    # Absolute path
cd ../                   # Go up one level
cd ~                     # Go to home directory
cd -                     # Go to previous directory

# Create directories
mkdir new_directory           # Create single directory
mkdir -p path/to/directory   # Create nested directories

# Remove files and directories
rm filename.txt              # Remove file
rm -r directory_name         # Remove directory recursively
rm -rf directory_name        # Force remove directory (use with caution)

File Content and Information

# View file contents
cat filename.txt       # Display entire file
head filename.txt      # Show first 10 lines
tail filename.txt      # Show last 10 lines
less filename.txt      # View file page by page

# Copy and move files
cp source.txt dest.txt           # Copy file
cp -r source_dir dest_dir        # Copy directory recursively
mv old_name.txt new_name.txt     # Rename/move file

Command History

# View command history
history                # Show command history
history | grep "git"   # Search history for specific commands

# Navigate history
!!                     # Run last command
!n                     # Run command number n from history
Ctrl+R                 # Reverse search through history

Shell Variables and Environment

Environment Variables

Shell variables store information that can be used by commands and scripts:

# View environment variables
echo $HOME             # Display home directory
echo $PATH             # Display PATH variable
env                    # Show all environment variables

# Set variables
export MY_VAR="hello world"    # Create/set environment variable
unset MY_VAR                   # Remove variable

# Common environment variables
echo $USER             # Current username
echo $PWD              # Current working directory
echo $SHELL            # Current shell

.env Files

Environment files (.env) store configuration variables for applications:

# Example .env file content
DATABASE_URL=postgresql://localhost:5432/mydb
API_KEY=your-secret-api-key
DEBUG=true
PORT=3000

To use .env files:

# Load variables from .env file
source .env                    # Load into current shell
export $(cat .env | xargs)     # Alternative loading method

# Use in scripts
#!/bin/bash
source .env
echo "Connecting to: $DATABASE_URL"

Using Variables in String Construction

# Variable substitution
NAME="John"
MESSAGE="Hello, $NAME!"              # Result: "Hello, John!"
MESSAGE="Hello, ${NAME}!"            # More explicit syntax

# Combining variables
BASE_PATH="/var/www"
PROJECT_NAME="myapp"
FULL_PATH="$BASE_PATH/$PROJECT_NAME"  # Result: "/var/www/myapp"

# Using variables in commands
USER="alice"
LOG_FILE="/var/log/${USER}_activity.log"
touch "$LOG_FILE"                     # Creates /var/log/alice_activity.log

Command Composition

Double Ampersand (&&) Operator

The && operator allows you to run commands sequentially, where the next command only runs if the previous one succeeds:

# Basic usage
cd project && npm install               # Change directory AND install if cd succeeds
mkdir temp && cd temp && touch file.txt # Chain multiple commands

# Practical examples
git add . && git commit -m "Update files" && git push    # Git workflow
npm test && npm run build && npm run deploy              # Build pipeline
docker build -t myapp . && docker run -p 3000:3000 myapp # Docker workflow

# Error handling
make clean && make build && make test || echo "Build failed!"

Other Useful Operators

# Semicolon (;) - run commands sequentially regardless of success/failure
cd /tmp; ls; pwd                       # Always runs all commands

# Double pipe (||) - run second command only if first fails
cat file.txt || echo "File not found"  # Show file or error message

# Pipe (|) - pass output of first command to second
ls -la | grep "txt"                    # List files and filter for .txt files
ps aux | grep "python"                 # Show processes and filter for Python

# Background execution (&)
long_running_script.sh &               # Run in background

Advanced Features

Command Substitution

# Capture command output in variables
CURRENT_DATE=$(date)
FILE_COUNT=$(ls | wc -l)
CURRENT_DIR=$(pwd)

echo "Today is $CURRENT_DATE"
echo "This directory has $FILE_COUNT files"

Redirection

# Output redirection
echo "Hello" > file.txt                # Write to file (overwrite)
echo "World" >> file.txt               # Append to file
ls > file_list.txt                     # Save command output to file

# Error redirection
command_that_fails 2> error.log       # Redirect errors to file
command > output.log 2>&1             # Redirect both output and errors

The shell provides a powerful foundation for system interaction and automation, enabling efficient file management, process control, and complex workflows through command composition and scripting.