Master Bash: Essential Variables, Operators, and Conditional Statements
This guide introduces Bash scripting fundamentals, covering predefined variables, declaration operators, and practical examples of single‑, double‑, and multi‑branch if statements for tasks such as checking user privileges, disk usage, and service status on Linux systems.
Bash (or shell) programming is the most widely used scripting language on Linux, and mastering its basic constructs can greatly improve productivity for anyone working in a Linux environment.
Predefined Variables
The following special variables are frequently used: $? – Exit status of the last command (0 means success). $$ – Process ID of the current shell. $! – Process ID of the most recent background command.
Declaration Operators
The declare builtin lets you set variable attributes: declare -i var – Declare an integer variable. declare -x var – Export the variable to the environment. declare -p var – Display the variable’s attributes and value.
Example: Simple Arithmetic
a=1
b=2
declare -i c=$a+$b
c=$(($a+$b)) # use double parentheses for arithmetic evaluationNote that arithmetic must be performed inside $(( )) because the shell treats everything as a string by default.
Conditional Statements
Single‑branch if
if [ condition ]; then
# commands
fiChecking for root user
#!/bin/bash
login_name=$(env | grep LOGNAME | cut -d "=" -f 2)
if [ "$login_name" != "root" ]; then
echo 'is not root'
fiChecking root partition usage
#!/bin/bash
result=$(df -h | grep sda1 | awk '{print $5}' | cut -d % -f 1)
if [ "$result" -lt 90 ]; then
echo 'the root dir is not full'
fiDouble‑branch if…else
if [ condition ]; then
# commands when true
else
# commands when false
fiTesting if Nginx is running
#!/bin/bash
result=$(ps aux | grep nginx | grep -v grep)
if [ -n "$result" ]; then
echo "$(date) nginx is ok !"
else
echo "$(date) nginx is not ok !"
sudo /etc/init.d/nginx start &>/dev/null
echo "$(date) restart nginx !!"
fiMulti‑branch if…elif…else
if [ condition1 ]; then
# commands
elif [ condition2 ]; then
# commands
else
# fallback commands
fiThese examples demonstrate how to use Bash variables, attribute declarations, and various forms of conditional logic to automate common system‑administration tasks.
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.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
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.
