Skip to main content

Command Palette

Search for a command to run...

Shell Scripting Concepts and Syntax — Variables, Conditions, and Loops (Part 2)

Published
5 min readView as Markdown

In the previous article, you learned what shell scripting is and how to write and execute a basic Bash script.
Now we take the next step and learn how Bash scripts actually become powerful.

In this part, we’ll cover:

  • Variables

  • Command substitution

  • Conditionals (if / else)

  • File, number, and string checks

  • Script parameters

  • Loops (for and while)

  • Reading user input

These concepts allow you to write flexible, reusable, and intelligent scripts.


Variables: Store Once, Use Everywhere

Variables allow you to store a value once and reuse it many times.

Example:

file_name="config.yaml"

Variable naming styles:

  • file_name (underscore – common)

  • fileName (camelCase)

Both are valid. Naming is a convention, not a rule.


Using Variables

To reference a variable:

echo "Using file $file_name to configure server"
  • $ tells Bash to read the variable value

  • Double quotes are recommended


Command Substitution: Save Command Output in a Variable

You can assign the output of a command to a variable.

Example:

config_files=$(ls config)

Now config_files contains whatever ls config outputs.

Using it:

echo "Here are all configuration files: $config_files"

When Commands Fail

If the directory doesn’t exist:

  • Bash prints an error

  • The variable becomes empty

This happens often in real environments and that’s why we need conditionals.


Conditionals: Preparing for Different Scenarios

Before running risky commands, we check conditions first.

Basic structure:

if [ condition ]; then
  commands
else
  other_commands
fi

File and Directory Conditions

Check if a directory exists:

if [ -d config ]; then
  echo "Reading config directory contents"
else
  echo "Config directory not found, creating one"
  mkdir config
fi
  • -d → directory exists

  • -f → file exists

  • -r → readable

  • -w → writable

  • -x → executable

  • -s → file is not empty

These checks protect your script from failures.


Number Comparisons

Used when working with counts, sizes, or metrics.

Examples:

  • -lt → less than

  • -gt → greater than

  • -le → less than or equal

  • -ge → greater than or equal

  • -ne → not equal

Example:

if [ "$file_count" -lt 10 ]; then
  echo "Safe to process files"
fi

String Comparisons

Used to compare text values.

Example:

if [ "$user_group" = "admin" ]; then
  echo "Admin access granted"
else
  echo "No permission"
fi
  • Single = → POSIX-compatible

  • Double == → Bash-specific


Multiple Conditions with elif

if [ "$user_group" = "nana" ]; then
  echo "Configure server"
elif [ "$user_group" = "admin" ]; then
  echo "Administer server"
else
  echo "Wrong user group"
fi

Script Parameters: Passing Values from Outside

Scripts can accept parameters at execution time.

Example execution:

./setup.sh admin config

Inside the script:

  • $1 → first parameter

  • $2 → second parameter

Example:

config_dir="$1"
user_group="$2"

This makes scripts configurable instead of hard-coded.


Using Parameters in Conditions

if [ -d "$config_dir" ]; then
  echo "Reading config directory"
  ls "$config_dir"
else
  echo "Creating directory"
  mkdir "$config_dir"
fi

Reading User Input

Instead of parameters, you can ask the user directly.

Example:

read -p "Please enter your password: " user_password
echo "Thanks for your password: $user_password"

Useful when:

  • Input is sensitive

  • Parameters are unknown

  • Interaction is required


Special Parameter Variables

  • $* → all parameters

  • $# → number of parameters

Example:

echo "Total params: $#"
echo "All params: $*"

Loops: Repeating Logic

When working with lists, you use loops.


for Loop — Iterate Over a List

Example:

for param in $*; do
  echo "$param"
done

How it works:

  • Each parameter is assigned to param

  • Loop runs once per parameter


Practical for Loop Example

for param in $*; do
  if [ -d "$param" ]; then
    echo "Directory found: $param"
    ls "$param"
  else
    echo "Not a directory: $param"
  fi
done

Perfect for:

  • Lists of files

  • Lists of servers

  • Lists of programs


while Loop — Run Until a Condition Changes

Unlike for, while loops run as long as a condition is true.


Infinite Loop Example

sum=0

while true; do
  read -p "Enter a score (Q to quit): " score

  if [ "$score" = "Q" ]; then
    break
  fi

  sum=$((sum + score))
  echo "Total score: $sum"
done

Key concepts:

  • while true → infinite loop

  • break → exit loop

  • $(( )) → numeric calculation


Arithmetic in Bash

Without $(( )), Bash treats values as strings.

Correct numeric addition:

sum=$((sum + score))

Single vs Double Brackets

  • [ condition ] → standard

  • [[ condition ]] → Bash-enhanced

With [[ ]]:

  • Quotes are optional

  • Safer string comparisons


Bash vs Other Automation Tools

Bash is powerful—but:

  • Syntax is complex

  • Hard to maintain at scale

Alternatives:

  • Python (more readable)

  • Configuration tools (like Ansible)

However, knowing Bash gives you a huge advantage, because:

  • You understand the foundation

  • You can choose the right tool

  • You can debug automation at any level


Final Takeaway

In this lecture, you learned how to:

  • Use variables

  • Capture command output

  • Write conditionals

  • Accept parameters

  • Read user input

  • Use loops effectively

  • Control execution flow

These concepts turn Bash scripts from simple command files into real automation tools.

More from this blog

devops

22 posts