CloudsArk
Bash Scripting Linux

Bash Conditions If Else

Learn practical bash conditions if else with Linux commands, verification steps, common mistakes, and related administrator guidance.

Bash Conditions If Else

Introduction

This Bash guide covers bash conditions if else with scripts that can be tested on a normal Linux host. The examples use safe defaults, quoted variables, and explicit error handling.

Basic Syntax

name="server1"
printf "host=%s\n" "$name"

The shell expands variables, runs commands, and uses exit codes to decide whether a step succeeded.

Practical Examples

#!/usr/bin/env bash
set -euo pipefail

path="/var/log"
if [[ -d "$path" ]]; then
  du -sh "$path"
fi

Real-World Script Example

#!/usr/bin/env bash
set -euo pipefail

target="${1:-/tmp}"
if [[ ! -e "$target" ]]; then
  echo "target does not exist: $target" >&2
  exit 1
fi

printf "checking %s\n" "$target"
ls -ld "$target"

Error Handling

if ! systemctl is-active --quiet sshd; then
  echo "sshd is not running" >&2
  exit 1
fi

Use clear messages and non-zero exits so cron, CI jobs, and monitoring tools can detect failure.

Testing the Script

bash -n script.sh
chmod +x script.sh
./script.sh /var/log
echo $?

Expected output:

checking /var/log
drwxr-xr-x. 12 root root 4096 May 30 09:55 /var/log
0

Common Mistakes

  • Making several changes at once, which hides the real cause.
  • Skipping logs or verification commands after a change.
  • Assuming the problem is fixed because one command returned successfully.

Best Practices

  • Use strict mode for administrative scripts.
  • Print useful errors to standard error.
  • Keep scripts idempotent when they change system state.
  • Validate inputs before running privileged commands.

Summary

Good Bash scripts are predictable: validate input, quote variables, handle errors, and test realistic failure cases before using them in automation.