Advanced Bash techniques for automation, optimization, and security

Memory and CPU

Monitoring memory and CPU usage is essential for maintaining system stability, especially in environments with high workloads or limited resources. Tools like top, htop, and vmstat provide real-time monitoring, whereas ps and /proc offer data for programmatic analysis.

For example, to monitor the memory and CPU usage of a specific process, use ps:

ps -o pid,comm,%cpu,%mem -p <PID>

This command displays the process ID, the command, and its percentage of CPU and memory usage. In a script, you can automate resource monitoring and trigger alerts if thresholds are exceeded (Listing 7).

Listing 7

Monitoring and Triggering

pid=1234
cpu_usage=$(ps -o %cpu= -p $pid)
mem_usage=$(ps -o %mem= -p $pid)
if (( $(echo "$cpu_usage > 80" | bc -l) )); then
  echo "Warning: Process $pid is using $cpu_usage% CPU."
fi
if (( $(echo "$mem_usage > 70" | bc -l) )); then
  echo "Warning: Process $pid is using $mem_usage% memory."
fi

For long-term monitoring, the sar utility (part of the sysstat package) records system activity, providing historical data for performance tuning. To view CPU and memory usage trends, use:

sar -u 1 5    # CPU usage
sar -r 1 5    # Memory usage

This data can guide decisions on scaling, such as upgrading hardware or distributing workloads across multiple servers.

Testing and Version Control

Ensuring the reliability and maintainability of shell scripts is crucial in production environments, particularly as scripts grow in complexity and integrate with larger systems. Testing and version control play pivotal roles in achieving these objectives. I'll describe how to implement unit testing for shell scripts using tools like bats, integrate shell scripts into CI/CD pipelines for automated testing and deployment, and follow best practices for version control in scripting projects.

Unit Testing

Unit testing is a critical step in verifying the correctness of your shell scripts. The Bash Automated Testing System (bats) is a lightweight testing framework specifically designed for shell scripts. You can use bats to write test cases for individual script functions or commands, ensuring they behave as expected under various conditions.

To get started, install bats on your Linux system. For most distributions, you can install it via a package manager:

sudo apt install bats  # Debian-based
sudo yum install bats  # RHEL-based

Alternatively, you can install bats using Git:

git clone https://github.com/bats-core/bats-core.git
cd bats-core
sudo ./install.sh /usr/local

Once bats is installed, create a test file with the .bats extension. For example, if you are testing a script called my_script.sh that calculates the sum of two numbers, your test file might look like the file in Listing 8.

Listing 8

Test File

# test_my_script.bats
@test "Addition works correctly" {
  result=$(./my_script.sh add 2 3)
  [ "$result" -eq 5 ]
}
@test "Handles missing arguments" {
  result=$(./my_script.sh add 2)
  [ "$result" = "Error: Missing arguments" ]
}

Run the tests with:

bats test_my_script.bats

The framework outputs a clear pass/fail summary, making it easy to identify issues. You can extend tests to cover edge cases, invalid inputs, and integration scenarios.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • Tutorial – Shell Scripting

    You do not need to learn low-level programming languages to become a real Linux power user. Shell scripting is all you need.

  • Perl: Network Backup

    Armed with just a rescue CD and a Perl script, you can back up a client’s hard disk across the wire.

  • Metadata in the Shell

    Armed with the right shell commands, you can quickly identify and evaluate file and directory metadata.

  • Tutorials – Shell Scripts

    Letting your scripts ask complex questions and give user feedback makes them more effective.

  • Bacula

    When backup jobs become too challenging for a script, the daemon-based free backup tool Bacula may be the answer.

comments powered by Disqus
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Subscribe to our ADMIN Newsletters

Support Our Work

Linux Magazine content is made possible with support from readers like you. Please consider contributing when you’ve found an article to be beneficial.

Learn More

News