Shell Scripting Revision

Shell Scripting Revision

ยท

5 min read

Here are Shell Scripting Revision Notes for quick reference. ๐Ÿš€


1. Basics of Shell Scripting

What is a Shell Script?

  • A shell script is a file containing a series of Linux commands.

  • It automates tasks that you would normally run manually in a terminal.

Shebang (#!)

  • The first line in a shell script specifies the interpreter:

      #!/bin/bash   # Bash shell
      #!/bin/sh     # POSIX shell
      #!/usr/bin/env python3  # Python script
    
  • To make the script executable:

      chmod +x script.sh
    
  • To run the script:

      ./script.sh
    

2. Variables in Shell

Defining Variables

name="Alice"
age=25

Accessing Variables

echo "Name: $name"
echo "Age: ${age}"

Read Input from User

echo "Enter your name:"
read username
echo "Hello, $username!"

Special Variables

VariableDescription
$0Script name
$1, $2, ...Arguments passed to script
$#Number of arguments
$@ or $*All arguments
$$Process ID of script
$?Exit status of last command

3. Conditional Statements

If-Else Statement

if [ "$age" -ge 18 ]; then
  echo "You are an adult."
else
  echo "You are a minor."
fi

String Comparisons

if [ "$name" = "Alice" ]; then
  echo "Welcome, Alice!"
fi

File Checks

ExpressionDescription
-e fileFile exists
-d dirDirectory exists
-f fileFile exists and is a regular file
-r fileFile is readable
-w fileFile is writable
-x fileFile is executable

Example:

if [ -f "data.txt" ]; then
  echo "File exists!"
else
  echo "File not found!"
fi

4. Loops in Shell Scripting

For Loop

for i in 1 2 3 4 5; do
  echo "Iteration $i"
done

While Loop

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

Until Loop

n=1
until [ $n -gt 5 ]; do
  echo "Number: $n"
  n=$((n + 1))
done

Loop Through a File

while read line; do
  echo "Line: $line"
done < file.txt

5. Functions in Shell Scripting

function greet() {
  echo "Hello, $1!"
}
greet "Alice"

6. Case Statement

echo "Enter a choice: "
read option

case $option in
  1) echo "You selected One" ;;
  2) echo "You selected Two" ;;
  *) echo "Invalid option" ;;
esac

7. Command Line Arguments

echo "Script Name: $0"
echo "First Argument: $1"
echo "Second Argument: $2"
echo "All Arguments: $@"
echo "Total Arguments: $#"

8. Input and Output Redirection

SymbolUsage
>Redirect output to a file (overwrite)
>>Append output to a file
<Read input from a file
2>Redirect errors to a file
&>Redirect both stdout and stderr

Example:

ls > output.txt    # Save output to file
ls >> output.txt   # Append output to file
cat < input.txt    # Read from file
ls 2> error.log    # Redirect errors
ls &> all.log      # Redirect both stdout & stderr

9. Background & Foreground Execution

  • Run a script in the background:

      ./script.sh &
    
  • Bring a process to the foreground:

      fg %1
    
  • List background jobs:

      jobs
    

10. Process Management

CommandDescription
ps auxList all processes
topMonitor system processes
kill <PID>Kill a process by PID
pkill <name>Kill a process by name
nohup command &Run a command in the background (ignore hangup signals)

Example:

kill $(pgrep firefox)

11. Scheduling Jobs (cron & at)

Cron Jobs (Repeated Execution)

  • Edit cron jobs:

      crontab -e
    
  • List cron jobs:

      crontab -l
    
  • Cron Job Syntax:

      * * * * * command_to_run
      โ”ฌ โ”ฌ โ”ฌ โ”ฌ โ”ฌ
      โ”‚ โ”‚ โ”‚ โ”‚ โ”‚
      โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ Day of the week (0 - 6) [Sunday = 0]
      โ”‚ โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€ Month (1 - 12)
      โ”‚ โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€ Day of the month (1 - 31)
      โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Hour (0 - 23)
      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Minute (0 - 59)
    

Example:
Run a script every day at 5 AM:

0 5 * * * /path/to/script.sh

at Command (One-time Execution)

  • Run a job at a specific time:

      echo "echo Hello" | at 14:30
    
  • List pending jobs:

      atq
    
  • Remove a job:

      atrm <job_id>
    

12. Networking in Shell

  • Ping a server:

      ping -c 4 google.com
    
  • Fetch an external IP address:

      curl ifconfig.me
    
  • Check open ports:

      netstat -tulnp
    

13. Debugging Shell Scripts

  • Run the script in debug mode:

      bash -x script.sh
    
  • Debug specific lines:

      set -x   # Enable debugging
      set +x   # Disable debugging
    

These revision notes cover the most important shell scripting concepts!

ย