Fundamentals of Bash
Bash Scripting Basics Guide
1. Introduction to Shell and Bash
A shell is an interface that allows users to interact with the operating system. It interprets the commands you enter and executes them.
Bash (Bourne Again Shell) is the most commonly used shell on Linux systems and is widely used for scripting, automating tasks, and managing system processes.
Bash is a command processor that typically runs in a text window where users type commands that cause actions. It's the default shell on most Linux distributions.
2. Other Common Shells
There are multiple types of shells in Linux, and here are a few common ones:
Bash (
/bin/bash
): Default shell for many Linux distributions.Zsh (
/bin/zsh
): An extended version of Bash, with more features.Ksh (
/bin/ksh
): Korn shell, known for its advanced scripting capabilities.Fish (
/usr/bin/fish
): A user-friendly shell with a focus on interactive features.
3. Checking and Changing the Current Shell
To see which shell you're currently using:
To change your shell temporarily:
To permanently change the default shell, you can use:
This command changes your default shell, but requires you to log out and log back in for the changes to take effect.
4. Basic Syntax of Bash Scripts
Before diving into an exercise, let’s quickly cover some of the essential components of a Bash script:
Shebang (
#!
): Tells the system what interpreter to use to execute the script. Most scripts will use#!/bin/bash
.Variables: Used to store and manipulate data.
Conditionals:
if
,else
,elif
used for decision-making.Loops:
for
,while
, anduntil
used to repeat actions.Input/Output Redirection: Redirecting input/output with operators (
>
,>>
,|
).
Basic Script Structure
5. Sample Script: System Information and Monitoring Tool
Exercise Objective:
This script will:
Create a directory.
Move a file into the directory.
Copy the file back out of the directory.
Display the file listing at each step.
Remove the directory and file (as a cleanup step).
6. How to Run the Script:
Open a terminal and create a new script file:
Paste the sample script into the file and save it.
Make the script executable:
Run the script:
Last updated