Linux Shell Programming with Bash and the vi Editor

Posted by Anonymous and classified in Computers

Written on in English with a size of 6.71 KB

🐚 Introduction to Shell Programming in Linux

Shell programming is the process of writing shell scripts—sequences of commands executed by the command-line interpreter (the shell, typically Bash) to automate tasks. It leverages command-line utilities, variables, and control flow structures to create powerful programs.

✍️ The vi Editor

The vi (or vim) editor is a text-based, modal editor crucial for writing shell scripts and editing configuration files in Linux. It operates in distinct modes:

ModeFunctionKey Commands
Command ModeThe default mode used for navigation, deletion, copying, and pasting.h, j, k, l for cursor movement; dd to delete a line.
Insert ModeUsed for typing and editing text.i (insert before cursor), a (append after cursor), o (open new line below).
Last-Line ModeUsed for saving, quitting, and searching. Entered by typing :.:w (write/save), :q (quit), :wq (save and quit), :q! (quit without saving).

📝 Shell Variables

Shell variables are named entities used to store data within a shell environment or a script.

  • Defining/Assigning: NAME="value" (Note: no spaces around the equals sign).
  • Accessing: Use the dollar sign ($) prefix.
  • Example:
    MY_VAR="Linux"; echo "The OS is $MY_VAR"
  • Special Variables (Positional Parameters): Used to access arguments passed to a script or function.

Special Variables (Positional Parameters)

VariableMeaningExample Use
$0The name of the script itself.echo $0
$1, $2, ...Positional arguments passed to the script.echo $1 (the first argument)
$#The total number of arguments passed.echo $#
$?The exit status (return code) of the most recently executed foreground command (0 for success, non-zero for failure).echo $?
$$The Process ID (PID) of the shell script.echo $$

🔄 I/O in Shell

Shell scripts manage Input/Output (I/O) through commands and redirection mechanisms.

  • Reading Input: The read command pauses the script and waits for user input, storing it in a variable.
    read -p "Enter username: " USERNAME
  • Output Redirection:
    • >: Redirects output to a file, overwriting it. Example: ls -l > output.txt
    • >>: Appends output to the end of a file. Example: echo "More data" >> output.txt
  • Input Redirection:
    • <: Takes input for a command from a file instead of the keyboard. Example: wc -l < data.txt
  • Piping (|): Connects the standard output of one command to the standard input of another.
    cat log.txt | grep ERROR | sort

🚦 Control Structures and Loops

These structures introduce logic flow, allowing scripts to make decisions and perform repetitive tasks.

Control Structures (Decision Making)

The if-elif-else structure executes commands based on the result of a test condition (often inside [ ] or [[ ]]).

if [ "$1" = "start" ]; then
    echo "Starting service..."
elif [ "$1" = "stop" ]; then
    echo "Stopping service..."
else
    echo "Usage: script {start|stop}"
fi

Loops (Repetition)

Common loop types:

Loop TypeFunctionSyntax Example
forIterates over a list of items (e.g., file names, sequence of numbers).for file in *.txt; do echo $file; done
whileRepeats a block of code as long as a specified condition is true.while [ $i -le 5 ]; do echo $i; i=$((i+1)); done
untilRepeats a block of code as long as a specified condition is false.until ping -c 1 $host; do sleep 5; done

📦 Subprograms (Functions)

Functions (subprograms) are reusable blocks of code defined within a script. They improve script organization and modularity.

# Define the function

backup_file () {
    # $1 here is the first argument passed to the function
    cp "$1" "$1.bak"
    echo "Backed up $1"
}

# Call the function
backup_file "config.conf"

* Arguments passed to the function are accessed using the local positional variables $1, $2, etc.

▶️ Creating & Executing Shell Scripts

  1. Creating the Script
    • Use an editor (e.g., vi) to create a file (e.g., check_status.sh).
    • The first line must be the Shebang line, which specifies the interpreter.
    • Example:
      #!/bin/bash
  2. Granting Execution Permission

    Scripts must have the execute permission set before they can be run directly.

    chmod +x check_status.sh
  3. Executing the Script

Execution Methods

Execution MethodCommandRequirementDescription
Direct Execution (Standard)./check_status.shRequires +x permission.Executes the script using the interpreter specified by the Shebang line.
Direct Interpretationbash check_status.shNo +x needed.Executes the script explicitly using the bash interpreter.
Sourcing. check_status.sh or source check_status.shNo +x needed.Executes the script within the current shell, allowing variables/functions to persist.

Related entries: