Forem

Sourav kumar
Sourav kumar

Posted on

Day 05/100 - Bash special commands (part-1)

Let's create a Bash script that demonstrates these special features step by step. The script will explain and showcase:

✅ /dev/null (The "black hole" of Linux)
✅ File descriptors: 0 (stdin), 1 (stdout), 2 (stderr)
✅ Redirections (>, >>, 2>, 2>&1, &> and |)
✅ commmand -v

Script: bash_special_features.sh

#!/bin/bash

<< Information ===================================================

# Bash Special Features Demo
# Author: Sourav Kumar
# Date: $(date +"%Y-%m-%d")
# Description: Demonstrates advanced Bash concepts

Information=======================================================

# Set strict mode for better error handling
set -euo pipefail  # Prevents script from continuing on errors

LOG_FILE="script.log"  # Log file for debugging

# -------------------------------
# Logging Function
# -------------------------------
log() {
    local timestamp
    timestamp=$(date +"%Y-%m-%d %H:%M:%S")
    echo "[$timestamp] $*" | tee -a "$LOG_FILE"
}

# -------------------------------
# Function to Check Command Existence
# -------------------------------
check_command() {
    if command -v "$1" > /dev/null 2>&1; then
        log "✅ $1 is installed"
    else
        log "❌ $1 is NOT installed. Please install it."
        return 1  # Exit with error status
    fi
}

# -------------------------------
# Start of Script Execution
# -------------------------------
log "🚀 Starting Bash Special Features Demo..."
log "🔹 File Descriptors, Redirections, and /dev/null"
echo "---------------------------------------------------------------"

# 1️⃣ Understanding File Descriptors
log "   - 0 = Standard Input (stdin)"
log "   - 1 = Standard Output (stdout)"
log "   - 2 = Standard Error (stderr)"

# 2️⃣ Demonstrating stdout (1) and stderr (2)
log "Running: ls /home > stdout.txt 2> stderr.txt"
ls /home > stdout.txt 2> stderr.txt
log "   - Standard Output saved in stdout.txt"
log "   - Standard Error saved in stderr.txt"

# 3️⃣ Redirecting both stdout and stderr to the same file
log "Running: ls /nonexistent_path > output.txt 2>&1"
ls /nonexistent_path > output.txt 2>&1 || log "⚠️ Error logged in output.txt"

# 4️⃣ Redirecting both stdout and stderr using &>
log "Running: ls /root &> combined_output.txt"
ls /root &> combined_output.txt || log "⚠️ Error logged in combined_output.txt"

# 5️⃣ Suppressing output using /dev/null
log "Running: ls / > /dev/null"
ls / > /dev/null
log "   - Standard Output is discarded"

log "Running: ls /nonexistent_path 2> /dev/null"
ls /nonexistent_path 2> /dev/null || log "⚠️ Error suppressed"

# 6️⃣ Using /dev/null to test command existence
check_command rsync

# 7️⃣ Using Pipe (|) to send stdout to another command
log "Running: ls / | grep etc"
ls / | grep etc || log "⚠️ 'etc' not found in /"

# -------------------------------
log "✅ Script Execution Completed ✅"
log "Check the output files: stdout.txt, stderr.txt, output.txt, combined_output.txt, and $LOG_FILE"

Enter fullscreen mode Exit fullscreen mode

What does /dev/null do?
/dev/null is a special file in Linux that acts as a "black hole."
Anything sent to /dev/null is discarded (i.e., it disappears and does not show up in the terminal).

Example 1: Redirecting Output to /dev/null

ls > /dev/null
Enter fullscreen mode Exit fullscreen mode

The ls command normally lists files in the current directory.
"> /dev/null" sends the output (file list) into the "black hole," so nothing appears on the screen.

Example 2: Suppressing Command Output

echo "Hello World" > /dev/null
Enter fullscreen mode Exit fullscreen mode

Normally, echo "Hello World" prints "Hello World" to the terminal.
With "> /dev/null", the output is discarded, so you see nothing.

Understanding File Descriptors and Redirection in Bash
In Bash, file descriptors and redirection help control where input and output go.

File Descriptors (FD)

FD Name Description
0 stdin Standard Input (Keyboard/Input File)
1 stdout Standard Output (Terminal/Log File)
2 stderr Standard Error (Error Messages)

Redirection Operators (>, >>)

Operator Description
">" Redirects output to a file (overwrites existing content)
">>" Appends output to a file (does not overwrite)

ls /home > stdout.txt 2> stderr.txt
Enter fullscreen mode Exit fullscreen mode

Redirect stdout and stderr separately
">" stdout.txt saves normal output.
"2>" stderr.txt saves errors separately.

Summary Table
Image description


Understanding command -v in Bash
The command -v command is used to check if a command exists and determine its path. It is useful in scripting to ensure that required tools are available before executing commands.

1. Basic Usage of command -v

command -v ls
Enter fullscreen mode Exit fullscreen mode

output

/bin/ls
Enter fullscreen mode Exit fullscreen mode

Explanation:

This checks whether ls exists in the system and returns its full path.
If the command is not found, it returns nothing.

2. Checking If a Command Exists in a Script

if command -v git > /dev/null 2>&1; then
    echo "Git is installed!"
else
    echo "Git is not installed. Please install it."
fi
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • command -v git checks if git is installed.
  • > /dev/null 2>&1 suppresses output.
  • If found, it prints "Git is installed!", otherwise, it prints an error message.

3. Using command -v to Get a Command Path

echo "Python is located at: $(command -v python3)"
Enter fullscreen mode Exit fullscreen mode

Output (if installed):

Python is located at: /usr/bin/python3
Enter fullscreen mode Exit fullscreen mode

Explanation:

This prints the full path of python3.

4. Assigning the Path to a Variable

PYTHON_PATH=$(command -v python3)
echo "Python is installed at: $PYTHON_PATH"
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Stores the path of python3 in PYTHON_PATH.
  • Prints the location of Python.

5. Using command -v with Multiple Commands

for cmd in docker kubectl terraform; do
    if command -v "$cmd" > /dev/null 2>&1; then
        echo "$cmd is installed"
    else
        echo "$cmd is not installed"
    fi
done
Enter fullscreen mode Exit fullscreen mode

Explanation:

This checks if docker, kubectl, and terraform are installed.


Difference Between command -v, which, and type

Image description

example

command -v echo  # Output: /bin/echo
which echo       # Output: /bin/echo
type echo        # Output: echo is a shell builtin
Enter fullscreen mode Exit fullscreen mode

Top comments (0)