Linux Shell Scripting Explained | TryHackme Linux Shells
This post is part of a Cybersecurity 101 series and focuses on Linux shells, their types, features, and how to use Bash scripting for automation.
Introduction to Linux Shells
Linux shells provide an efficient and resource-friendly way to interact with the OS via the command-line interface (CLI).
Different types of Linux shells include Bash (/bin/bash
), Dash (/usr/bin/dash
), Zsh, and Fish.
Each shell offers unique features such as auto-completion, spell correction, syntax highlighting, and user-friendliness.
To check the current shell:
echo $SHELL
To switch shells, use:
sudo chsh -s /usr/bin/dash
Popular Linux Shells and Their Features
Bash, SH, and Zsh are widely used due to their robust scripting capabilities.
Zsh offers advanced features like syntax highlighting and user-friendly customization.
Fish Shell is the most user-friendly shell and is available for Windows, macOS, and Linux.
Basic Linux Commands in Shell
PWD: Displays the current directory.
LS: Lists directory contents.
Nano: Opens a file for editing.
Introduction to Bash Scripting
Bash scripts automate repetitive tasks and have the .sh
extension.
Shebang (#!
) specifies the interpreter (#!/bin/bash
).
Comments use #
.
Variables are declared as variable=value
. For strings, values are enclosed in quotes.
Use echo
to print output to the terminal.
Script Example: Searching for a Flag in Log Files
Purpose: Automates searching for a specific string in .log
files.Script Components:
- Variables: Set directory and flag string.
- Echo: Prints progress messages.
- For Loop: Iterates over
.log
files. - If Statement: Uses
grep -q
to search for the flag. - Output: Prints the filename if the flag is found.
- Permission Command:
chmod +x script.sh # Grants execute permission
sudo ./script.sh # Runs the script with elevated permissions
Key Bash Commands Explained
History: Displays previously executed commands
history
chmod +x: Grants execute permission to a script.
For Loops:
- Iterate through numbers:
for i in {1..10}; do echo $i; done
- Iterate through files:
for file in /var/log/*.log; do echo $file; done
Advanced Example: Locker Script
Purpose: Verifies user identity with multiple factors before granting access.Key Features:
- Username verification.
- Custom logic for identity validation.
TryHackMe Linux Shells | Room Answers
Room answers can be found here.