Day 39: Bash Scripting Basics: Learn Variables and Command-Line Arguments

🧠 What is Bash Scripting?

Bash scripting allows you to automate tasks in Unix/Linux environments using a sequence of shell commands inside a script file (usually ending with .sh).

Example:

#!/bin/bash
echo "Hello, DevOps!"

🔹 Variables in Bash

User-defined Variables

You can define variables without a $ and access them with a $:

name="Shaharyar"
echo "Welcome $name"
  • No spaces around =

  • Variables are loosely typed (strings by default)

🧪 Arithmetic with Variables:

a=10
b=5
echo $((a + b))     # Outputs: 15

🔹 System (Environment) Variables

These are predefined variables that affect the system environment and behavior.

VariableDescription
$HOMEHome directory of the current user
$USERCurrent logged-in user
$PATHList of directories the shell searches for commands
$SHELLDefault shell used
$PWDCurrent working directory

Example:

echo "You are in $PWD"

🔹 Command-Line Arguments

These allow you to pass data into scripts when they are run.

Syntax:

./script.sh arg1 arg2

In the script:

  • $0 = Script name

  • $1 = First argument

  • $2 = Second argument

  • $# = Number of arguments

  • $@ = All arguments

Example Script:

#!/bin/bash
echo "Script name: $0"
echo "Hello, $1! Welcome to $2."

Run:

./welcome.sh Shaharyar DevOps
# Output: Hello, Shaharyar! Welcome to DevOps.

🧭 What’s Next?

More into bash scripting

0
Subscribe to my newsletter

Read articles from Shaharyar Shakir directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shaharyar Shakir
Shaharyar Shakir