Day: 3 (Part :- 2) More deep into the shell scripting

1. Leverage Here Documents for Configuration Management:

  • Here documents (<< operator) allow you to embed multi-line content directly within your script. This is incredibly useful for storing configuration settings or complex commands within the script itself.

Bash

#!/bin/bash
server_list=(server1 server2 server3)

<<CONFIG
for server in "${server_list[@]}"; do
  ssh $server "sudo systemctl restart service_name"
done
CONFIG

# Execute the configuration block
eval "$CONFIG"

2. Utilize Process Substitution for Dynamic Command Output:

  • Process substitution allows you to capture the output of a command and use it as input for another command within the script. This enables powerful one-liners for tasks like filtering or manipulating data.

Bash

#!/bin/bash
running_processes=$(ps -eo pid,comm | grep "nginx")  # Capture process info
pids_to_kill=$(echo "$running_processes" | awk '{print $1}')  # Extract PIDs

# Kill processes using captured PIDs
kill $pids_to_kill

3. Embrace Command Aliases for Improved Workflow:

  • Define custom aliases (using the alias command) for frequently used or complex commands. This promotes efficiency and readability within your scripts.

Bash

alias dstat="sudo dstat -cdnmgt"  # Custom alias for detailed system statistics

# Script using the alias
dstat &  # Start monitoring in the background
sleep 60  # Wait for a minute
killall dstat  # Stop monitoring

4. Explore Advanced String Manipulation:

  • Shell scripting offers powerful string manipulation capabilities using tools like cut, awk, sed, and parameter expansion. Mastering these tools allows you to parse complex data streams or manipulate file contents within scripts.

Bash

# Extracting IP address from network interface config (example)
ip_address=$(ifconfig eth0 | grep "inet addr" | awk '{print $2}')
echo "IP Address: $ip_address"

5. Delve into Regular Expressions (regex) for Powerful Pattern Matching:

  • Regular expressions (regex) provide a powerful way to search and manipulate text based on specific patterns. This is invaluable for tasks like log file analysis, data validation, and file content filtering within scripts.

Bash

#!/bin/bash
log_file="server.log"

# Filter lines with error messages
error_lines=$(grep -E "ERROR|WARN" $log_file)

# Process or analyze the filtered error lines
echo "Found the following errors:"
echo "$error_lines"