20 Essential Shell Functions for File Management, System Monitoring, and Automation
This article presents twenty practical custom Bash functions covering file existence checks, directory listings, size retrieval, command verification, date and time handling, colored output, delays, root detection, IP fetching, random string generation, port checking, service control, and email sending, each with concise code examples for easy integration into scripts.
Overview
This reference collects twenty reusable Bash functions that address common scripting tasks such as file and directory handling, system inspection, text formatting, and simple service control. Each function is self‑contained and can be sourced into a script or interactive shell.
File and Directory Checks
Check if a file exists
file_exists() {
[ -f "$1" ] && echo "File exists." || echo "File does not exist."
}Check if a directory exists
dir_exists() {
[ -d "$1" ] && echo "Directory exists." || echo "Directory does not exist."
}List files in a directory (non‑recursive)
list_files() {
find "$1" -maxdepth 1 -type f -print
}Count files in a directory
count_files() {
find "$1" -type f | wc -l
}Get the most recently modified file in the current directory
last_modified_file() {
ls -t | head -n 1
}Empty a file
empty_file() {
> "$1"
}File Information
Show file size in human‑readable format
get_file_size() {
du -sh "$1" 2>/dev/null | cut -f1
}System Utilities
Test whether a command is available
command_exists() {
command -v "$1" >/dev/null 2>&1
}Print the current date (YYYY‑MM‑DD)
current_date() {
date +"%Y-%m-%d"
}Print the current time (HH:MM:SS)
current_time() {
date +"%H:%M:%S"
}Calculate the difference between two dates (in days)
date_diff() {
# Arguments: start_date end_date (format accepted by GNU date)
start=$(date -d "$1" +%s)
end=$(date -d "$2" +%s)
echo $(( (end - start) / 86400 ))
}Print coloured text
print_color() {
local text=$1
local color=$2
case "$color" in
red) echo -e "\033[31m${text}\033[0m" ;;
green) echo -e "\033[32m${text}\033[0m" ;;
yellow) echo -e "\033[33m${text}\033[0m" ;;
blue) echo -e "\033[34m${text}\033[0m" ;;
*) echo "$text" ;;
esac
}Delay execution for a given number of seconds
delay() {
sleep "$1"
}Check whether the script runs as root
is_root() {
[ "$(id -u)" -eq 0 ] && echo "Root user" || echo "Not root user"
}Retrieve the primary IP address of the host
get_ip() {
hostname -I | awk '{print $1}'
}Generate a random alphanumeric string (default length 10)
generate_random_string() {
local length=${1:-10}
tr -dc 'a-zA-Z0-9' </dev/urandom | fold -w "$length" | head -n 1
}Test whether a TCP port on a host is open
is_port_open() {
nc -zv "$1" "$2" 2>/dev/null | grep -q open
}Service Management (systemd)
Restart a systemd service
restart_service() {
systemctl restart "$1"
}Check service status silently (returns 0 if active)
service_status() {
systemctl is-active --quiet "$1"
}Email Sending
Send a simple email using the local mail command
send_email() {
# Arguments: subject body recipient
echo "$2" | mail -s "$1" "$3"
}Usage Notes
All functions assume a GNU/Linux environment with standard utilities ( find, date, nc, systemctl, etc.). Adjust paths or replace commands when running on non‑systemd distributions or minimal containers. The send_email function requires a correctly configured mail (or mailx) utility; otherwise it will fail silently.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
