Bash logo

Bash Scripting Beginner

Unix Shell Engine — automation blueprints, pipeline stream redirection, system permission management, and cross-platform automation via native Linux or Windows WSL frameworks.

1 Environment Setup & The Shebang

Bash is the default execution interface for Linux environments. On Windows platforms, you can safely execute identical scripts utilizing **WSL (Windows Subsystem for Linux)** or Git Bash, bypassing native PowerShell formatting completely. Every script must explicitly declare its execution engine via a header construct called **Shebang**.

sh · script.sh
#!/bin/bash
# The line above is the Shebang, telling the system kernel to evaluate this file using Bash.

echo "Shell execution sequence initialized."

2 File System Navigation Core

Interacting with the system requires traversing directory structures. Unlike Windows paths which utilize backslashes and drive letters (C:\), Unix environments map all elements down from a single root slash infrastructure.

pwd Print Working Directory: outputs your precise active directory path location /home/ivan/projects
ls -la Lists all directory files, revealing hidden entities along with permission metadata Lists flags and dots
cd /path Changes your current shell context location. Use "cd .." to climb up one layer cd /var/log/nginx
mkdir -p Creates new structural folder systems, automatically creating intermediate parent directories mkdir -p app/src/main
WSL Note Inside Windows WSL, your local storage drives are automatically mounted under the mnt tree cd /mnt/c/Users/
clear Flushes all printed terminal buffer lines away, cleaning up your visibility view Resets terminal viewport

3 File Manipulation & Permissions

Files must explicitly carry execution permissions to run as scripts. The operating system calculates security rights based on three user categories: **User (Owner), Group, and Others**.

sh · deployment.sh
touch log.txt              # Instantiates a fresh, empty text file block
cp log.txt backup.txt      # Duplicates file payloads into target location
mv backup.txt /tmp/        # Moves or renames target entity parameters
rm -rf /tmp/backup.txt     # Forcefully removes files or directories recursively

# Modifies asset access rights: grants execution capabilities (+x) to the active script
chmod +x script.sh

4 Variables & User Inputs

Variables store dynamic configurations within a script context. **CRITICAL WARNING:** You must never leave trailing whitespaces around the assignment operator token (=); otherwise, the shell engine parses the target variable name as an executable system application command.

sh · inputs.sh
USER_NAME="Ivan"           # Correct declaration string allocation
echo "Target developer: $USER_NAME"

echo "Provide database connection token:"
read DB_TOKEN              # Halts thread to intercept typed user input parameters
echo "Token registered: $DB_TOKEN"

5 Conditional Statements (If & Test)

Branching flows rely on condition blocks evaluated via the [ ] syntax (which internally calls the system tool test). Strings use standard algebraic symbols, but numerical evaluations require specific flag operators.

sh · logic.sh
FILE_COUNT=10

if [ $FILE_COUNT -gt 5 ]; then
    echo "Threshold exceeded. Intrinsic matrix execution required."
else
    echo "Payload limits stable."
fi

# Common flags: -gt (Greater Than), -lt (Less Than), -eq (Equal), -d (Directory exists)

6 Loops & Iteration Routines

Loops automate repetitive tasks, such as scanning text arrays or batch-modifying server log layouts, by processing structures over a structured collection block.

sh · loops.sh
# Iterates through a defined numerical scalar progression range matrix
for i in {1..3}; do
    echo "Processing server backup instance #$i"
done

# Scans files matching wildcard configurations inside active paths
for FILE in *.txt; do
    echo "Found text log data: $FILE"
done
**Be mindful of Line Endings cross-platform!** Scripts created on Windows carry invisible carriage return markers (\r\n, CRLF). Running these files inside Linux or WSL throws obscure syntax crashes because Bash looks for pure Unix line breaks (\n, LF). Fix these files using the dos2unix tool.

7 I/O Redirections, Pipes & Grep

The true power of Bash lies in standard stream manipulation. By leveraging the pipe operator (|), you can redirect the text output of one script or command to serve as the direct input for the next processing block.

sh · streams.sh
echo "Log anomaly caught." > output.log   # Overwrites file contents entirely
echo "Appended debug log line." >> output.log # Appends text to the end of the file

# Intercepts raw process streams, filtering exclusively for specific error flags
cat output.log | grep "ERROR"

8 Process Control & System Signaling

Every execution task runs in its own memory container track monitored via a unique **PID (Process ID)**. Bash lets you shift tasks to the background or terminate stalled processes instantly.

sh · processes.sh
node app.js &       # The trailing ampersand spawns the runtime in the background

ps aux             # Prints an absolute global snapshot map of all live system processes
kill -9 1245       # Sends SIGKILL signal to forcefully terminate the process with PID 1245
With fundamental scripting structures clear, your next engineering advancements involve cross-compiling deployment workflows using **Docker containers** or building complex **CI/CD pipeline scripts**.