Cyber Security /Linux Fundamentals / Lesson
Cyber Security

Shell Fundamentals

Learn the fundamentals of Linux shells, Bash commands, variables, quoting, pipes, redirection, conditions, loops, functions, exit codes, shell scripts and secure shell scripting practices.

🎯

Learning Objectives

["Explain what a shell is and how it relates to the terminal.","Understand Bash as a common Linux shell.","Understand command syntax, arguments, options and exit codes.","Use shell variables safely.","Understand quoting and command substitution.","Use pipes and input\/output redirection.","Understand conditions and loops in shell scripts.","Understand shell functions and positional parameters.","Recognize common shell-security risks.","Write simple defensive shell scripts in an authorized environment."]

📖

Lesson Content

Shell Fundamentals

The shell is one of the most important tools for working with Linux.
It provides an interface through which users can execute commands, work with
files, inspect systems, automate tasks and interact with operating-system
services.

For cybersecurity professionals, shell knowledge is particularly valuable because
many Linux servers, security tools, cloud environments and administration systems
are managed through command-line interfaces.


1. What Is a Shell?

A shell is a command interpreter that accepts commands from a user or script and
communicates with the operating system to perform requested operations.

The shell is different from the physical or graphical terminal application.
A terminal provides an interface through which you can interact with a shell.

Common Linux shells include:

  • Bash
  • Zsh
  • Fish
  • Ksh
  • Dash

Bash, which means Bourne Again SHell, is one of the most widely encountered shells
in Linux environments.


2. Terminal Versus Shell

TermMeaning
TerminalAn interface through which commands can be entered and output displayed.
ShellA command interpreter that processes commands.
CommandAn instruction executed through the shell.
ScriptA file containing a sequence of commands and programming logic.

3. The Shell Prompt

When a shell is ready to receive a command, it displays a prompt.
The appearance of the prompt varies between systems.

A prompt might look similar to:

student@linux-lab:~$

The prompt may provide information such as the current username, computer name
and current directory.

The dollar sign $ commonly represents a normal user shell, while
a root shell may use #. Prompt appearance is configurable, so these
symbols should not be treated as an absolute rule.


4. Basic Command Structure

A simple command commonly contains:

command [options] [arguments]

For example:

ls -la /var/log

Here:

  • ls is the command.
  • -la contains options.
  • /var/log is an argument.

Not every command requires options or arguments.


5. Command Help

Linux provides several ways to learn how a command works.

command --help
man command

For example:

ls --help
man ls

Reading documentation before executing unfamiliar commands is an important
administrative and security habit.


6. Exit Codes

Commands normally return an exit status indicating whether an operation succeeded
or failed.

In shell scripting, the special variable $? can be used to inspect
the exit status of the most recently executed command.

echo $?

Conventionally, an exit code of 0 represents success, while a
non-zero value usually indicates an error or another condition.


7. Variables

Shell variables allow information to be stored and reused.

name="Dwallnet"

echo "$name"

When assigning a variable, there should normally be no spaces around the equals
sign.

The dollar sign is used when retrieving the value of a variable.


8. Environment Variables

Environment variables provide information that can be inherited by processes
started by a shell.

Common examples include:

echo "$HOME"
echo "$USER"
echo "$PATH"
echo "$SHELL"

These variables can provide information about the current user, home directory,
shell and executable search path.


9. The PATH Variable

The PATH environment variable contains directories that the shell
searches when locating executable commands.

echo "$PATH"

If a command is not located in the current directory or another explicitly
specified location, the shell uses the configured search path to locate it.

Poorly configured PATH values can create security risks, especially when
untrusted directories are placed before trusted system directories.


10. Quoting

Quoting controls how the shell interprets text.

Single Quotes

echo 'Hello $USER'

Single quotes generally prevent variable expansion and most shell interpretation
inside the quoted text.

Double Quotes

echo "Hello $USER"

Double quotes generally allow variable expansion while protecting spaces and
many special characters from word splitting.

Correct quoting is extremely important in shell scripting.


11. Command Substitution

Command substitution allows the output of one command to be used as part of
another command.

Modern shell syntax commonly uses:

today=$(date)

echo "$today"

The command inside $() runs and its output becomes part of the
surrounding command.


12. Pipes

A pipe connects the standard output of one command to the standard input of
another command.

Example:

ls -la | grep ".conf"

This allows commands to be combined into useful processing chains.

Pipes are widely used in system administration, log analysis and security
investigation.


13. Output Redirection

Shells can redirect command output into files.

Overwrite a File

echo "Dwallnet Linux Lab" > lab.txt

Append to a File

echo "Second line" >> lab.txt

The difference is important: > normally replaces the existing
file contents, while >> appends to the file.


14. Input Redirection

The less-than symbol can redirect a file into a command’s standard input.

command < input.txt

The exact behavior depends on the command being used.


15. Standard Input, Output and Error

Unix-like systems commonly use three standard streams:

  • stdin — standard input
  • stdout — standard output
  • stderr — standard error

Understanding these streams makes shell commands and scripts much easier to
control.

For example:

command > output.txt
command 2> errors.txt

The second example redirects standard error.


16. Command Chaining

Commands can be combined using operators such as && and
;.

AND Operator

command1 && command2

The second command normally runs only if the first command succeeds.

Semicolon

command1 ; command2

The second command runs regardless of whether the first command succeeds.


17. Conditions

Shell scripts can make decisions using conditional statements.

#!/bin/bash

name="Dwallnet"

if [ "$name" = "Dwallnet" ]; then
    echo "Name matched."
else
    echo "Name did not match."
fi

Conditions allow scripts to respond differently depending on system state or
input.


18. Numeric Conditions

Shell scripts can also compare numeric values.

#!/bin/bash

count=10

if [ "$count" -gt 5 ]; then
    echo "Count is greater than five."
fi

Common numeric comparison operators include:

  • -eq — equal
  • -ne — not equal
  • -gt — greater than
  • -lt — less than
  • -ge — greater than or equal
  • -le — less than or equal

19. Loops

Loops allow a script to repeat an operation.

A simple Bash loop:

#!/bin/bash

for item in one two three
do
    echo "$item"
done

Loops are useful for processing controlled collections of files, values or
administrative records.


20. While Loops

A while loop continues while a specified condition remains true.

#!/bin/bash

count=1

while [ "$count" -le 3 ]
do
    echo "Count: $count"
    count=$((count + 1))
done

Students should always ensure that loop conditions eventually become false when
appropriate.


21. Functions

Functions allow reusable logic to be grouped together.

#!/bin/bash

show_message() {
    echo "Dwallnet Cyber Security Lab"
}

show_message

Functions improve organization and reduce unnecessary duplication in scripts.


22. Positional Parameters

Shell scripts can receive arguments from the command line.

For example, $1 represents the first positional argument,
$2 the second, and $# represents the number of
arguments.

#!/bin/bash

echo "First argument: $1"
echo "Number of arguments: $#"

Input received from users should always be treated as untrusted until properly
validated.


23. Reading User Input

The read command can collect input from a user.

#!/bin/bash

read -r -p "Enter your name: " name

printf 'Hello, %s\n' "$name"

The -r option prevents backslash interpretation by
read.


24. The Shebang

A shell script often begins with a shebang line identifying the interpreter.

#!/bin/bash

The shebang helps the operating system determine which interpreter should be
used when the script is executed in an appropriate manner.


25. Shell Script Permissions

A script may need execute permission before it can be launched directly.

For example, in an authorized lab:

chmod +x lab-script.sh

The script can then be run using its appropriate path.

Always verify the contents of a script before granting execute permission,
especially when the file came from another person or an external source.


26. Shell Scripts and Automation

Shell scripts can automate routine administrative tasks such as:

  • Checking disk usage
  • Collecting system information
  • Checking service status
  • Processing logs
  • Creating reports
  • Performing controlled backups
  • Checking configuration files

Automation should be tested carefully before being used on important systems.


27. Safe Error Handling

Shell scripts should be designed to detect failures where appropriate.

Bash provides options such as:

set -e
set -u
set -o pipefail

These options can help scripts fail more predictably, but they should be
understood before being applied because shell behavior can be affected by the
specific structure of the script.


28. Command Injection

Command injection is a security vulnerability in which untrusted input is
incorrectly incorporated into commands executed by a system.

For example, a web application that takes user input and directly places that
input into a shell command can create serious security risks.

The safest general approach is to avoid shell execution when it is unnecessary.
When operating-system commands are genuinely required, applications should use
appropriate APIs, strict allowlists and careful input validation.


29. Why eval Requires Extreme Caution

Shells can interpret dynamically constructed commands, but this behavior can
be dangerous when untrusted data becomes part of the command.

Students should avoid using eval with untrusted input.
Dynamic command construction should not be treated as a substitute for proper
input validation.


30. Quoting and Security

Incorrect quoting can cause unexpected word splitting, wildcard expansion or
other shell interpretation.

Compare:

echo $name

with:

echo "$name"

Using quotes around variables is generally a good defensive habit when the value
is intended to be treated as one piece of text.


31. Secrets in Shell Scripts

Passwords, API keys, private tokens and other secrets should not normally be
hard-coded into shell scripts.

Risks include:

  • Accidental source-code exposure
  • Backup exposure
  • Command-history exposure
  • Log exposure
  • Unauthorized access by other users

Use appropriate secret-management mechanisms for production environments.


32. Shell History

Shell history is useful because it allows users to review and repeat commands.
However, it can also expose sensitive information if secrets are placed directly
into command lines.

Students should therefore avoid entering passwords, tokens or other sensitive
information directly into commands when safer input mechanisms are available.


33. PATH Hijacking Concept

If a system searches an unsafe directory before trusted system directories,
an unexpected executable with the same name as a legitimate command could
potentially be executed.

This is one reason administrators should understand the PATH environment variable
and avoid blindly modifying it.


34. Shell Metacharacters

Shells recognize special characters that can change how commands are interpreted.
Examples include:

|   &   ;   >   <   $   *   ?   (   )

These characters have different meanings depending on context.

Understanding shell syntax is important both for administration and for
recognizing command-injection risks.


35. Shell Fundamentals for Cybersecurity

Security professionals use shell commands for tasks such as:

  • Inspecting running processes
  • Examining logs
  • Checking network configuration
  • Reviewing file permissions
  • Inspecting installed packages
  • Checking disk usage
  • Investigating system configuration
  • Automating defensive checks

Shell knowledge should therefore be viewed as a core Linux cybersecurity skill.


36. Safe Shell-Scripting Example

The following example accepts a simple text value and displays it safely.
It does not execute the supplied value as an operating-system command.

#!/bin/bash

read -r -p "Enter your name: " name

if [ -z "$name" ]; then
    echo "No name was entered."
    exit 1
fi

printf 'Hello, %s\n' "$name"

Notice that the value is printed as data rather than being interpreted as a
command.


37. PHP Example — Safe Shell Input Concept

PHP applications should avoid unnecessary shell execution. When a system command
is genuinely required, user input should not be blindly concatenated into a
command.

The following example demonstrates validation of a simple identifier without
executing it:

<?php

$identifier = 'student-001';

if ( preg_match( '/^[a-zA-Z0-9_-]+$/', $identifier ) ) {

    echo 'Identifier accepted: ' .
        htmlspecialchars(
            $identifier,
            ENT_QUOTES,
            'UTF-8'
        );

} else {

    echo 'Invalid identifier.';
}

The example deliberately does not execute an operating-system command.


38. Authorized Shell Lab

All shell exercises in this course should be performed only on systems that the
student owns, administers or has explicit permission to use.

Lab Tasks:

  1. Create a directory named shell-lab.
  2. Move into the directory.
  3. Create a file named notes.txt.
  4. Write two harmless lines into the file.
  5. Use cat to display the file.
  6. Use grep to search for one of the words.
  7. Create a simple Bash script.
  8. Use a variable in the script.
  9. Add an if condition.
  10. Run the script inside the authorized laboratory.

39. Security Investigation Scenario

Imagine that a security analyst is investigating a Linux workstation where an
unexpected script has appeared.

The analyst should consider:

  • Who created the file?
  • When was the file created?
  • What permissions does it have?
  • What does the script contain?
  • Who owns the file?
  • Was the file executed?
  • Are there related logs?
  • Was the script introduced by an approved administrator?

The analyst should preserve evidence and follow the organization’s incident
response procedures rather than immediately modifying or deleting potentially
important evidence.


40. Shell Scripting Best Practices

  • Use clear variable names.
  • Quote variables appropriately.
  • Validate external input.
  • Avoid unnecessary shell execution.
  • Avoid eval with untrusted data.
  • Do not hard-code secrets.
  • Use trusted command paths where appropriate.
  • Check command exit codes.
  • Document important scripts.
  • Test scripts in a safe environment before production use.
  • Use least privilege.
  • Keep scripts under appropriate access control.

41. Practical Assignment

Build a Simple System Information Script

Create a harmless Bash script that displays:

  • Current username
  • Hostname
  • Current directory
  • Current date
  • Linux kernel information

Suggested commands to research:

whoami
hostname
pwd
date
uname -a

The script should only collect and display information from your authorized
laboratory machine.


42. Review Questions

  1. What is a shell?
  2. What is the difference between a terminal and a shell?
  3. What is Bash?
  4. What is the purpose of the PATH variable?
  5. What is command substitution?
  6. What does a pipe do?
  7. What is the difference between > and >>?
  8. What are stdin, stdout and stderr?
  9. What is an exit code?
  10. Why is shell quoting important?
  11. What is command injection?
  12. Why should secrets not be hard-coded into shell scripts?
  13. What is the purpose of a shell function?
  14. Why should shell scripts be tested before production use?

43. Key Takeaways

  • The shell is a command interpreter used to interact with Linux.
  • Bash is one of the most common Linux shells.
  • Shell commands can be combined using pipes and redirection.
  • Variables allow scripts to store and reuse information.
  • Conditions and loops provide programming logic.
  • Functions make shell scripts easier to organize and maintain.
  • Exit codes help scripts determine whether commands succeeded.
  • Correct quoting is important for reliable and secure scripts.
  • Untrusted input should never be blindly incorporated into shell commands.
  • Secrets should not be hard-coded into scripts or exposed through command history.
  • Shell scripting is a valuable defensive cybersecurity skill.
  • All security-related shell activities must be properly authorized.

44. Conclusion

Shell fundamentals provide the foundation for efficient Linux administration and
cybersecurity work. By understanding commands, variables, pipes, redirection,
conditions, loops, functions and secure scripting practices, students can work
more confidently in Linux environments.

The most important principle is to understand what a command or script will do
before executing it, especially when administrative privileges are involved.

Module 4 Complete: Linux Fundamentals.

The next stage of the Cyber Security course is
Module 5 — Web Security Fundamentals.

💻

Code Example

<?php

$identifier = 'student-001';

if ( preg_match( '/^[a-zA-Z0-9_-]+$/', $identifier ) ) {

    echo 'Identifier accepted: ' .
        htmlspecialchars(
            $identifier,
            ENT_QUOTES,
            'UTF-8'
        );

} else {

    echo 'Invalid identifier.';
}
⭐

Key Takeaways

["The shell is a command interpreter used to interact with Linux.","Bash is one of the most common Linux shells.","Shell commands can be combined using pipes and redirection.","Variables allow scripts to store and reuse information.","Conditions and loops provide programming logic.","Functions make shell scripts easier to organize and maintain.","Exit codes help scripts determine whether commands succeeded.","Correct quoting is important for reliable and secure scripts.","Untrusted input should never be blindly incorporated into shell commands.","Secrets should not be hard-coded into scripts or exposed through command history.","Shell scripting is a valuable defensive cybersecurity skill.","All security-related shell activities must be properly authorized."]

Enjoying this lesson?

Sign in to your Dwallnet Academy student account to track your learning progress and mark lessons as complete.

Sign In to Track Progress