Variables, arguments, loops, and exit status

3.3 Turning Commands into a Script (Weight: 4)

📘Linux Essentials (LPI 010-160)


1. Variables in Shell Scripts

What is a Variable?

A variable is a name that stores a value.
The stored value can be used later in the script.

Variables make scripts flexible because values can change without modifying the whole script.

Examples of stored values:

  • usernames
  • directory paths
  • numbers
  • command output
  • file names

Creating Variables

Variables are created using the following format:

VARIABLE_NAME=value

Example:

USERNAME=admin
DIRECTORY=/var/log
COUNT=10

Important rules:

  • No space before or after =
  • Variable names are case sensitive
  • Variable names usually use uppercase letters

Valid examples:

USER_NAME=admin
LOG_DIR=/var/log
FILE_COUNT=5

Invalid example:

USER NAME=admin

Spaces are not allowed in variable names.


Accessing Variable Values

To use a variable value, the $ symbol is used.

Example:

echo $USERNAME

If:

USERNAME=admin

Output:

admin

Example script:

#!/bin/bashUSER_NAME=admin
echo "The current user is $USER_NAME"

Output:

The current user is admin

Using Curly Braces with Variables

Sometimes variables are written with curly braces.

Example:

${VARIABLE_NAME}

Example:

FILE=report
echo ${FILE}.txt

Output:

report.txt

This prevents confusion when adding text around variables.


Command Substitution

Variables can also store command output.

Syntax:

VARIABLE=$(command)

Example:

DATE=$(date)
echo $DATE

This stores the result of the date command inside the variable.

Example script:

#!/bin/bashCURRENT_USER=$(whoami)
echo "Logged in user: $CURRENT_USER"

Environment Variables

Environment variables are variables already defined by the system.

Common examples:

$HOME
$PATH
$USER
$SHELL

Example:

echo $HOME

Output example:

/home/admin

These variables are available to scripts automatically.


2. Arguments in Shell Scripts

What are Script Arguments?

Arguments are values passed to a script when it is executed.

This allows the same script to work with different inputs.

Example:

./script.sh file1.txt

Here:

file1.txt

is the argument.


Positional Parameters

Arguments are stored in special variables called positional parameters.

VariableMeaning
$0script name
$1first argument
$2second argument
$3third argument

Example script:

#!/bin/bashecho "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"

Run:

./script.sh file1 file2

Output:

Script name: ./script.sh
First argument: file1
Second argument: file2

Number of Arguments

The variable $# shows the number of arguments.

Example:

echo "Number of arguments: $#"

Example run:

./script.sh file1 file2 file3

Output:

Number of arguments: 3

All Arguments

Two special variables store all arguments.

$@

Represents all arguments individually.

$*

Represents all arguments as a single string.

Example:

echo "Arguments: $@"

Example Script Using Arguments

#!/bin/bashFILE=$1echo "Checking file: $FILE"ls -l $FILE

Run:

./checkfile.sh test.txt

This script checks a file given as an argument.

This is commonly used in IT tasks such as:

  • checking log files
  • processing backup files
  • verifying configuration files

3. Loops in Shell Scripts

What is a Loop?

A loop repeats a set of commands multiple times.

Loops are useful for tasks like:

  • processing multiple files
  • checking system services
  • monitoring directories
  • performing repeated administrative operations

Linux shell scripts mainly use:

  • for loops
  • while loops

For Loop

A for loop runs commands for each item in a list.

Syntax:

for variable in list
do
commands
done

Example:

for file in file1 file2 file3
do
echo "Processing $file"
done

Output:

Processing file1
Processing file2
Processing file3

Example: Processing Log Files

#!/bin/bashfor logfile in /var/log/*.log
do
echo "Checking $logfile"
done

This loop processes every log file in /var/log.

This is common in IT environments for:

  • log monitoring
  • security analysis
  • automated checks

While Loop

A while loop repeats commands while a condition is true.

Syntax:

while condition
do
commands
done

Example:

COUNT=1while [ $COUNT -le 5 ]
do
echo "Number: $COUNT"
COUNT=$((COUNT+1))
done

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Example: Monitoring a Service

#!/bin/bashwhile true
do
echo "Checking system status"
sleep 10
done

This script repeatedly checks system status every 10 seconds.

Such loops are used for:

  • system monitoring
  • service checks
  • automated scripts

4. Exit Status

What is Exit Status?

Every Linux command returns a status code after execution.

This code shows whether the command succeeded or failed.

Exit CodeMeaning
0Success
Non-zeroError or failure

Example:

ls /home

If successful → exit status = 0

If directory does not exist → exit status ≠ 0


Checking Exit Status

The special variable $? stores the exit status of the last command.

Example:

ls /home
echo $?

Example output:

0

If command fails:

ls /unknown
echo $?

Output example:

2

Using Exit Status in Scripts

Scripts often check exit status to determine the next action.

Example:

#!/bin/bashmkdir /backupif [ $? -eq 0 ]
then
echo "Directory created successfully"
else
echo "Directory creation failed"
fi

Explanation:

  • mkdir runs
  • $? checks if the command succeeded
  • script prints the result

Using exit Command

Scripts can manually set an exit status using the exit command.

Syntax:

exit status_code

Example:

exit 0

Means successful completion.

Example:

exit 1

Means error.


Example Script with Exit Status

#!/bin/bashFILE=$1if [ -f $FILE ]
then
echo "File exists"
exit 0
else
echo "File not found"
exit 1
fi

This script checks whether a file exists.

This is commonly used in IT tasks such as:

  • validating configuration files
  • checking backup availability
  • verifying deployment files

Important Exam Points

Students preparing for Linux Essentials (010-160) should remember:

Variables

  • Store values in scripts
  • Access using $VARIABLE
  • No spaces around =
  • Can store command output

Arguments

  • Passed when executing scripts
  • $0 = script name
  • $1 $2 $3 = arguments
  • $# = number of arguments
  • $@ = all arguments

Loops

Used to repeat commands.

Common loops:

  • for
  • while

Loop structure:

for item in list
do
commands
done

or

while condition
do
commands
done

Exit Status

  • Every command returns a status code
  • 0 = success
  • non-zero = failure
  • $? stores last command status
  • exit sets script exit code

Summary

In Linux shell scripting:

  • Variables store data that scripts use.
  • Arguments allow scripts to accept input from users.
  • Loops repeat commands automatically.
  • Exit status indicates whether commands succeed or fail.

These features allow administrators to create powerful scripts for tasks like:

  • processing log files
  • checking system configuration
  • monitoring services
  • validating files
  • automating administrative tasks

Understanding these concepts is essential for passing the Linux Essentials (LPI 010-160) exam and for writing effective shell scripts in Linux environments.

Buy Me a Coffee