How to Learn Bash Scripting and Use It in Termux — Complete Guide (2026)
- Introduction — Why Bash Scripting Matters in Termux
- What is Bash and How Does It Work in Termux?
- Setting Up Termux for Bash Scripting
- Bash Scripting Fundamentals — Variables, Input, and Conditions
- Loops, Functions, and File Handling in Bash
- Real-World Bash Scripts You Can Run in Termux Right Now
- Common Errors and Fixes
- Pro Tips for Bash Scripting in Termux
- Comparison Table — Bash vs Python vs Fish for Scripting
- FAQ
- Conclusion
// 00 — Introduction: Why Bash Scripting Matters in Termux
If you have been using Termux on your Android device for any amount of time, you have already been using bash scripting — you just may not have realized it. Every time you type pkg update, run a Python script, or chain two commands together with &&, you are using bash. Learning bash scripting in Termux is one of the single most powerful upgrades you can make to your Android terminal workflow, and in this complete guide written by Rixon Xavier, you are going to learn everything from the very beginning.
Bash — short for Bourne Again SHell — is the default shell in Termux and the most widely used scripting language in the Linux world. It is the glue that holds the entire Unix ecosystem together. Security professionals use bash scripts to automate reconnaissance. Developers use bash to set up environments, manage files, and run build pipelines. System administrators use bash to handle everything from backups to log rotation. And on Android with Termux, you can do all of these things — no laptop required, no root needed.
The best part about learning bash scripting in Termux is that you are learning a skill that transfers directly to every Linux server, every Kali Linux installation, and every Unix-based system on the planet. The commands and scripting patterns you learn in Termux on your phone work identically on enterprise servers running Ubuntu, Debian, and CentOS. You are not learning a toy environment — you are learning real Linux on your Android phone.
By the end of this guide, you will understand how bash works, how to write your own scripts from scratch, how to use variables, loops, conditions, and functions, and you will have several real working scripts you can run in Termux right now. Whether you are a complete beginner or someone who has dabbled in the terminal but never written a full script, this guide covers everything you need to go from zero to confident bash scripter — all from your Android phone.
// 01 — What is Bash and How Does It Work in Termux?
Before you write your first bash script, it is worth understanding exactly what bash is and why it matters. Bash is a command-line interpreter — a program that reads commands you type (or commands stored in a file) and executes them. When you open Termux and see a prompt waiting for your input, you are looking at bash. Every command you type goes through bash, which interprets it and tells the operating system what to do.
The Difference Between the Terminal and Bash
Many beginners confuse the terminal with bash. They are not the same thing. The terminal (Termux, in your case) is the application — the window you see on your screen. Bash is the program running inside that terminal that actually processes your commands. Termux uses bash as its default shell, which is why everything you type in Termux is bash by default.
What is a Bash Script?
A bash script is simply a plain text file that contains a sequence of bash commands. Instead of typing commands one by one, you put them all in a file, and bash executes them in order from top to bottom. This is powerful because you can automate complex, multi-step tasks with a single command. A script that might take you ten minutes of manual typing every day can be reduced to one command that runs in seconds.
Every bash script starts with a special first line called a shebang:
#!/data/data/com.termux/files/usr/bin/bash
This line tells the system which interpreter to use to run the script. On regular Linux systems you would use #!/bin/bash, but in Termux the bash binary lives at a different path. Always use the Termux-specific shebang shown above for scripts you write inside Termux.
#!/usr/bin/env bash as a more portable shebang that works in both Termux and regular Linux systems. This is the recommended approach if you plan to share your scripts.How Bash Reads and Executes Scripts
When you run a bash script, bash reads the file line by line from top to bottom. It executes each line as a command, in order. If a line fails, bash will either stop (depending on your settings) or continue to the next line. You can control this behavior using flags and error handling, which we will cover later in this guide. Understanding this top-to-bottom execution model is fundamental to writing bash scripts that behave predictably.
Bash also supports comments using the # character. Any line that starts with # (except the shebang) is ignored by bash. Use comments liberally to explain what your script does — your future self will thank you.
#!/usr/bin/env bash
# This is a comment — bash ignores this line
# Script name: hello.sh
# Author: Rixon Xavier — HYDRA TERMUX
# Purpose: Print a welcome message
echo "Welcome to HYDRA TERMUX!"
echo "You are learning bash scripting in Termux."
echo "This is line 3 of output."
// 02 — Setting Up Termux for Bash Scripting
Before you write any scripts, you need to make sure your Termux environment is properly set up. A clean, updated Termux installation with the right tools makes bash scripting much smoother. This section walks you through everything you need to do before writing your first script.
Step 1 — Update and Upgrade Termux
Always start with a fresh update. This ensures you have the latest versions of bash and all supporting tools.
pkg update && pkg upgrade -y
Step 2 — Install a Text Editor
To write bash scripts, you need a text editor. Termux includes nano by default, which is perfect for beginners. You can also install vim or micro depending on your preference.
# Install nano (easiest for beginners)
pkg install nano -y
# OR install vim (more powerful)
pkg install vim -y
# OR install micro (modern, beginner-friendly)
pkg install micro -y
Step 3 — Check Your Bash Version
Verify that bash is installed and check its version. Termux ships with a recent version of bash that supports all modern scripting features.
bash --version
You should see output similar to:
GNU bash, version 5.2.21(1)-release (aarch64-unknown-linux-android)
Copyright (C) 2022 Free Software Foundation, Inc.
Step 4 — Create a Scripts Folder
Keep your scripts organized by creating a dedicated folder. This makes them easy to find and manage.
# Create a scripts directory in your home folder
mkdir -p ~/scripts
# Navigate into it
cd ~/scripts
# Verify you're in the right place
pwd
# Output: /data/data/com.termux/files/home/scripts
Step 5 — Write and Run Your First Script
Create the file
Use nano to create a new script file called hello.sh
Write your script
Add the shebang line and your commands, then save with Ctrl+X → Y → Enter
Make it executable
Run chmod +x hello.sh to give the file execute permissions
Run your script
Execute it with ./hello.sh or bash hello.sh
# Create the script
nano hello.sh
# Paste this content into nano:
#!/usr/bin/env bash
echo "Hello from HYDRA TERMUX!"
echo "Bash scripting is running on Android!"
echo "Current date: $(date)"
echo "Current user: $USER"
# Save: Ctrl+X then Y then Enter
# Make it executable
chmod +x hello.sh
# Run it
./hello.sh
Expected output:
Hello from HYDRA TERMUX!
Bash scripting is running on Android!
Current date: Fri Feb 28 11:30:00 UTC 2026
Current user: u0_a135
// 03 — Bash Scripting Fundamentals — Variables, Input, and Conditions
Now that your environment is set up and you have run your first script, it is time to learn the core building blocks of bash scripting. These fundamentals — variables, user input, and conditional logic — are the foundation of every useful bash script you will ever write in Termux.
Variables in Bash
Variables store data that you can reference and reuse throughout your script. In bash, you create a variable by writing its name, an equals sign, and its value — with no spaces around the equals sign. This is one of the most common mistakes beginners make, so remember: no spaces around =.
#!/usr/bin/env bash
# Creating variables — NO spaces around =
name="Rixon Xavier"
blog="hydratermux.blogspot.com"
year=2026
is_learning=true
# Reading variables — use $ prefix
echo "Author: $name"
echo "Blog: $blog"
echo "Year: $year"
# Variables inside strings — use curly braces for clarity
echo "Welcome to ${name}'s blog!"
# Command substitution — store command output in a variable
current_date=$(date)
current_dir=$(pwd)
echo "Date: $current_date"
echo "Working directory: $current_dir"
Special Built-in Variables
Bash has several special variables that are automatically set and very useful in scripts:
#!/usr/bin/env bash
echo "Script name: $0" # Name of the script itself
echo "First argument: $1" # First argument passed to script
echo "Second argument: $2" # Second argument
echo "All arguments: $@" # All arguments as a list
echo "Number of arguments: $#" # Count of arguments passed
echo "Last exit code: $?" # Exit code of last command (0 = success)
echo "Process ID: $$" # PID of the current script
User Input with read
The read command lets your script pause and wait for the user to type something. This makes your scripts interactive.
#!/usr/bin/env bash
# Basic input
echo "Enter your name:"
read username
echo "Hello, $username! Welcome to HYDRA TERMUX."
# Input with prompt on same line (-p flag)
read -p "Enter your favorite tool: " tool
echo "Nice! $tool is a great choice."
# Silent input for passwords (-s flag hides typing)
read -s -p "Enter your secret key: " secret
echo "" # New line after silent input
echo "Key received. Length: ${#secret} characters."
# Input with a timeout (-t flag)
read -t 10 -p "Quick! Enter something (10 seconds): " fast_input
if [ $? -eq 0 ]; then
echo "You entered: $fast_input"
else
echo "Timed out!"
fi
Conditional Statements — if, elif, else
Conditions let your script make decisions. The basic structure is if [ condition ]; then ... fi. The space inside the square brackets is required — this is another very common beginner mistake.
#!/usr/bin/env bash
read -p "Enter a number: " num
# Compare numbers
if [ "$num" -gt 100 ]; then
echo "That's a big number!"
elif [ "$num" -gt 50 ]; then
echo "Over 50 — decent!"
elif [ "$num" -gt 0 ]; then
echo "Positive but small."
else
echo "Zero or negative."
fi
# String comparison
read -p "Are you a beginner? (yes/no): " answer
if [ "$answer" = "yes" ]; then
echo "Welcome! Start with the basics."
elif [ "$answer" = "no" ]; then
echo "Great — let's go deeper!"
else
echo "Please answer yes or no."
fi
# Check if a file exists
if [ -f "$HOME/scripts/hello.sh" ]; then
echo "hello.sh exists!"
else
echo "File not found."
fi
# Check if a directory exists
if [ -d "$HOME/scripts" ]; then
echo "Scripts directory exists."
fi
-gt (greater than), -lt (less than), -eq (equal), -ne (not equal), -ge (greater or equal), -le (less or equal) for numbers. Use = and != for strings.// 04 — Loops, Functions, and File Handling in Bash
Once you have mastered variables and conditions, the next major leap in your bash scripting journey is loops and functions. These are what transform simple scripts into powerful automation tools. Loops let you repeat tasks automatically. Functions let you organize your code into reusable blocks. Together, they make your Termux scripts dramatically more capable.
For Loops
A for loop repeats a block of commands for each item in a list. This is one of the most commonly used constructs in bash scripting.
#!/usr/bin/env bash
# Loop over a simple list
for tool in nmap hydra metasploit netcat curl wget; do
echo "Tool: $tool"
done
# Loop with a number range
for i in {1..10}; do
echo "Count: $i"
done
# C-style for loop
for (( i=0; i<5; i++ )); do
echo "Iteration: $i"
done
# Loop over all .sh files in current directory
for script in *.sh; do
echo "Found script: $script"
echo " Size: $(wc -c < "$script") bytes"
done
# Loop over lines in a file
for line in $(cat ~/scripts/list.txt); do
echo "Processing: $line"
done
While Loops
A while loop keeps running as long as a condition is true. This is useful for monitoring tasks, retry logic, and interactive menus.
#!/usr/bin/env bash
# Basic while loop
count=1
while [ $count -le 5 ]; do
echo "Round $count"
count=$((count + 1))
done
# Interactive menu loop — runs until user quits
while true; do
echo ""
echo "=== HYDRA TERMUX MENU ==="
echo "1) Show date and time"
echo "2) Show current directory"
echo "3) List files"
echo "4) Quit"
echo ""
read -p "Choose (1-4): " choice
case $choice in
1) echo "Date: $(date)" ;;
2) echo "Directory: $(pwd)" ;;
3) ls -la ;;
4) echo "Goodbye!"; break ;;
*) echo "Invalid choice. Try again." ;;
esac
done
Functions in Bash
Functions let you define reusable blocks of code. Define them once at the top of your script and call them as many times as you need. This keeps your code clean, readable, and maintainable.
#!/usr/bin/env bash
# Define functions at the top
# Simple function — no arguments
greet() {
echo "==========================="
echo " HYDRA TERMUX - Welcome!"
echo "==========================="
}
# Function with arguments ($1, $2, etc.)
install_package() {
local package_name="$1" # 'local' keeps variable inside function
echo "Installing: $package_name ..."
pkg install "$package_name" -y
if [ $? -eq 0 ]; then
echo "✅ $package_name installed successfully!"
else
echo "❌ Failed to install $package_name."
fi
}
# Function that returns a value
get_file_count() {
local dir="$1"
local count=$(ls "$dir" | wc -l)
echo $count # 'return' in bash only accepts 0-255, use echo instead
}
# Call your functions
greet
install_package "nmap"
file_count=$(get_file_count "$HOME")
echo "Files in home: $file_count"
File Handling in Bash
Bash scripts frequently need to read, write, and manipulate files. Here are the essential file operations you will use in your Termux scripts:
#!/usr/bin/env bash
# Write to a file (overwrites existing content)
echo "Log started: $(date)" > ~/scripts/log.txt
# Append to a file (adds to existing content)
echo "New entry: $(date)" >> ~/scripts/log.txt
# Read a file line by line
while IFS= read -r line; do
echo "Line: $line"
done < ~/scripts/log.txt
# Check if file exists before reading
logfile="$HOME/scripts/log.txt"
if [ -f "$logfile" ]; then
echo "Reading $logfile..."
cat "$logfile"
else
echo "Log file not found."
fi
# Count lines, words, and characters
echo "Lines: $(wc -l < "$logfile")"
echo "Words: $(wc -w < "$logfile")"
echo "Chars: $(wc -c < "$logfile")"
# Search inside a file
grep "error" "$logfile" || echo "No errors found."
# Delete a file safely
if [ -f "$logfile" ]; then
rm "$logfile"
echo "Log file deleted."
fi
// 05 — Real-World Bash Scripts You Can Run in Termux Right Now
Theory is important, but the best way to truly learn bash scripting in Termux is to write and run scripts that actually do something useful. This section gives you five complete, real-world bash scripts that you can copy, paste into Termux, and use immediately. Each one is fully commented so you understand every line.
Script 1 — Termux Auto-Update Script
This script automatically updates all Termux packages and shows a summary of what was updated.
#!/usr/bin/env bash
# update.sh — Auto-update all Termux packages
# Author: HYDRA TERMUX | hydratermux.blogspot.com
echo "=============================="
echo " HYDRA TERMUX Auto-Updater"
echo "=============================="
echo "Started: $(date)"
echo ""
# Update package lists
echo "[1/2] Updating package lists..."
pkg update -y
# Upgrade all installed packages
echo ""
echo "[2/2] Upgrading packages..."
pkg upgrade -y
echo ""
echo "=============================="
echo "✅ Update complete!"
echo "Finished: $(date)"
echo "=============================="
Script 2 — System Info Script
This script displays detailed information about your Android device and Termux environment.
#!/usr/bin/env bash
# sysinfo.sh — Display Termux system information
divider="──────────────────────────────"
echo "=============================="
echo " HYDRA TERMUX — System Info"
echo "=============================="
echo ""
echo "📱 DEVICE INFO"
echo "$divider"
echo "Hostname : $(hostname)"
echo "User : $USER"
echo "Shell : $SHELL"
echo "Bash version : ${BASH_VERSION}"
echo ""
echo "💾 STORAGE"
echo "$divider"
df -h "$HOME" | awk 'NR==2 {print "Total: "$2"\nUsed: "$3"\nFree: "$4"\nUsage: "$5}'
echo ""
echo "🧠 MEMORY"
echo "$divider"
free -h 2>/dev/null || echo "Memory info not available"
echo ""
echo "📦 TERMUX PACKAGES"
echo "$divider"
echo "Installed packages: $(pkg list-installed 2>/dev/null | wc -l)"
echo ""
echo "📅 DATE & TIME"
echo "$divider"
echo "$(date)"
echo "Uptime: $(uptime | awk -F'up' '{print $2}' | awk -F',' '{print $1}')"
echo ""
echo "=============================="
echo "✅ Done — HYDRA TERMUX"
echo "=============================="
Script 3 — Batch File Organizer
This script automatically sorts files in a directory into subfolders by their file extension.
#!/usr/bin/env bash
# organizer.sh — Sort files by extension into subfolders
TARGET_DIR="${1:-$HOME/storage/downloads}"
echo "Organizing files in: $TARGET_DIR"
echo ""
# Check directory exists
if [ ! -d "$TARGET_DIR" ]; then
echo "❌ Directory not found: $TARGET_DIR"
exit 1
fi
cd "$TARGET_DIR" || exit 1
moved=0
for file in *; do
# Skip if it's a directory
[ -d "$file" ] && continue
# Get the file extension (lowercase)
ext="${file##*.}"
ext="${ext,,}"
# Skip files with no extension
[ "$ext" = "$file" ] && continue
# Create folder if it doesn't exist
mkdir -p "$ext"
# Move the file
mv "$file" "$ext/"
echo " Moved: $file → $ext/"
((moved++))
done
echo ""
echo "✅ Done! Moved $moved files."
Script 4 — Network Scanner (Educational)
This educational script uses ping to check which hosts are reachable on your local network.
#!/usr/bin/env bash
# pingscan.sh — Educational ping sweep of local subnet
# For use on YOUR OWN network only
read -p "Enter subnet to scan (e.g. 192.168.1): " subnet
echo ""
echo "Scanning $subnet.1 to $subnet.254 ..."
echo "This may take a minute..."
echo ""
alive=0
for host in $(seq 1 254); do
ip="$subnet.$host"
# Send 1 ping with 1 second timeout
if ping -c 1 -W 1 "$ip" >/dev/null 2>&1; then
echo "✅ ALIVE: $ip"
((alive++))
fi
done
echo ""
echo "Scan complete. $alive host(s) responded."
Script 5 — Backup Script
This script creates a timestamped backup of your Termux scripts folder.
#!/usr/bin/env bash
# backup.sh — Backup your Termux scripts folder
SOURCE="$HOME/scripts"
BACKUP_DIR="$HOME/backups"
TIMESTAMP=$(date +"%Y-%m-%d_%H-%M-%S")
BACKUP_FILE="$BACKUP_DIR/scripts_backup_$TIMESTAMP.tar.gz"
echo "================================"
echo " HYDRA TERMUX Backup Script"
echo "================================"
echo ""
# Check source exists
if [ ! -d "$SOURCE" ]; then
echo "❌ Source directory not found: $SOURCE"
exit 1
fi
# Create backup directory
mkdir -p "$BACKUP_DIR"
# Create the backup archive
echo "Creating backup..."
tar -czf "$BACKUP_FILE" -C "$HOME" scripts/
if [ $? -eq 0 ]; then
size=$(du -sh "$BACKUP_FILE" | cut -f1)
echo ""
echo "✅ Backup created successfully!"
echo " File: $BACKUP_FILE"
echo " Size: $size"
echo " Time: $(date)"
else
echo "❌ Backup failed!"
exit 1
fi
// 06 — Common Errors and Fixes
Error: Permission Denied
You forgot to make your script executable. Fix it with:
chmod +x your_script.sh
./your_script.sh
Error: bad interpreter: No such file or directory
Your shebang path is wrong for Termux. Use this instead of #!/bin/bash:
#!/usr/bin/env bash
Error: syntax error near unexpected token
Usually caused by Windows-style line endings (CRLF). Fix it with:
pkg install dos2unix -y
dos2unix your_script.sh
Error: [ : missing ]
You are missing a space inside your brackets. Bash requires spaces inside [ ]:
# ❌ WRONG
if ["$name" = "Rixon"]; then
# ✅ CORRECT — space after [ and before ]
if [ "$name" = "Rixon" ]; then
Error: Unbound variable
You referenced a variable that was never set. Always quote variables and check they are defined:
# Use a default value if variable is empty
name="${username:-Guest}"
echo "Hello, $name"
// 07 — Pro Tips for Bash Scripting in Termux
set -e at the top of your script to make it exit immediately if any command fails. Add set -u to catch unset variables. Together they prevent silent failures."$variable" not $variable. Unquoted variables break if they contain spaces or special characters. This is the single habit that will save you the most debugging time.pkg install shellcheck -y and run shellcheck your_script.sh to automatically find bugs and style issues in your bash scripts before running them.echo 'export PATH="$HOME/scripts:$PATH"' >> ~/.bashrc && source ~/.bashrc so you can run any script from anywhere without typing the full path.trap 'rm -f /tmp/tempfile' EXIT to automatically clean up temporary files when your script exits — even if it crashes or the user presses Ctrl+C.bash -x your_script.sh to see every command as it executes. This is the fastest way to find exactly where a script is going wrong.$(( expression )). For example: result=$(( 5 * 10 + 3 )). For decimals, pipe through bc: echo "scale=2; 10/3" | bc.// 08 — Comparison Table: Bash vs Python vs Fish for Scripting in Termux
| Feature | Bash | Python | Fish |
|---|---|---|---|
| Default in Termux | ✅ Yes | ❌ No (install needed) | ❌ No (install needed) |
| Best for system tasks | ✅ Excellent | ⚠️ Moderate | ⚠️ Limited |
| Beginner friendly | ⚠️ Moderate | ✅ Very easy | ✅ Easy (interactive) |
| File manipulation | ✅ Excellent | ✅ Excellent | ⚠️ Basic |
| Network scripting | ✅ Good | ✅ Excellent | ❌ Poor |
| Portability | ✅ Universal | ✅ High | ⚠️ Fish only |
| Execution speed | ✅ Very fast | ⚠️ Slower startup | ✅ Fast |
| String handling | ⚠️ Tricky | ✅ Excellent | ✅ Good |
| Error handling | ⚠️ Manual | ✅ Built-in exceptions | ⚠️ Limited |
| Best use case | System automation, pipelines | Data processing, APIs | Interactive shell |
// FAQ — Bash Scripting in Termux
chmod +x your_script.sh before running the script. Alternatively, you can always run any bash script without execute permission using bash your_script.sh directly. The ./script.sh syntax requires execute permission, but bash script.sh does not.#!/usr/bin/env bash as your shebang line. This makes your scripts portable across both Termux and regular Linux systems. Scripts that use the Termux-specific shebang #!/data/data/com.termux/files/usr/bin/bash will only work in Termux. Using env bash ensures maximum compatibility.~/.bashrc. For example, add bash ~/scripts/welcome.sh to the end of your .bashrc file using nano. Every time you open a new Termux session, that script will run automatically. Be careful not to add scripts that take a long time or require user input, as this will delay your terminal every time you open it.pkg install cronie -y, then start the cron daemon with crond. Edit your crontab with crontab -e and add a schedule line. For example, 0 * * * * bash ~/scripts/update.sh runs your update script at the top of every hour. Note that Termux must be running in the background for cron jobs to execute.// 09 — Conclusion: Start Writing Bash Scripts in Termux Today
You have now covered everything you need to start writing real bash scripts in Termux — from the very basics of what bash is, through variables, conditions, loops, and functions, all the way to five complete real-world scripts you can run right now. Bash scripting in Termux is one of the most valuable skills you can develop as an Android power user, Linux learner, or cybersecurity student.
The key to getting good at bash scripting is the same as getting good at anything: practice. Open Termux right now, create a new .sh file, and start with something small. Maybe a script that greets you by name. Then add a condition. Then a loop. Then a function. Each small addition builds your understanding, and before you know it, you will be writing scripts that genuinely save you hours of manual work every week.
Remember that every bash script you write in Termux is transferable. The skills you build on your Android phone work on every Ubuntu server, every Kali Linux installation, and every cloud VM you will ever encounter. You are not just learning a phone trick — you are building a professional Linux skill on the device you already have in your pocket.
Bookmark this guide on hydratermux.blogspot.com and come back whenever you need a reference. Share it with anyone learning Termux or Linux for the first time. And stay tuned for more advanced guides covering bash script automation for security tools, API interaction from the terminal, and building full CLI applications in bash — all from your Android device.
mkdir -p ~/scripts && cd ~/scripts && nano first.sh, write your first script, and run it. The best time to start is right now..jpg)
Comments
Post a Comment