Posts

Showing posts with the label bash script

Bash Yes No Prompt: 7 Proven Patterns and 5 Mistakes

Image
A bash yes no prompt is a read -r -p "Question? [y/N] " ans followed by a case on the answer. The short version that most tutorials show works for a quick test, but it treats "yolo" as yes, loops forever when there is no terminal and silently skips the question when the script is piped. This guide shows a confirm function that handles all of that, plus Yes/No/Cancel, single-key answers, timeouts, select menus and unattended runs with -y . Every example was run on 2026-10-23 in a debian:trixie container with GNU bash 5.2.37 and dash as /bin/sh . The answers were typed on a real pseudo-terminal (util-linux script ), so the output below is exactly what a user sees at each bash yes no prompt, including the typed answer. Contents The classic bash yes no prompt and its problems A reusable bash yes no prompt function with a default Bash yes no prompt with Cancel in a loop Single key, timeout and select menu Bash yes no prompt in pipes, cron and CI POSIX sh version ...

How to Use Exit Codes in Linux: A Comprehensive Guide

Image
Introduction Exit codes in Linux are essential indicators that provide feedback on the success or failure of executed commands or scripts. Whether you're debugging a script, automating system tasks, or handling errors effectively, understanding exit codes can significantly enhance your workflow. This guide will explain what exit codes are, how to use them, and why they are crucial for scripting and automation. What Are Exit Codes in Linux? Understanding Exit Codes Exit codes are numeric values returned by a process upon its termination. They help determine if a command executed successfully or encountered an error. Why Are Exit Codes Important? They provide feedback on command execution. Useful for debugging scripts. Allow automation scripts to handle failures gracefully. Common Exit Codes and Their Meanings Exit Code Meaning Description 0 Success Command executed successfully. 1 General error Command failed due to an unspecified reason. 2 Misuse of shell built-ins Syntax error or ...

Optimizing Bash Scripts for Speed and Efficiency

Image
Introduction Bash scripting is an indispensable skill for system administrators, developers, and tech enthusiasts. However, as projects scale, inefficient scripts can lead to slower performance and higher resource usage. Optimizing Bash scripts for speed and efficiency ensures your scripts run smoothly, saving time and computational power. In this guide, we’ll explore proven strategies, from basic principles to advanced techniques, to help you write faster, leaner scripts. Why Optimize Bash Scripts? Efficient Bash scripts offer multiple benefits: Speed: Reduce execution time for time-critical tasks. Resource Efficiency: Lower CPU and memory usage. Readability: Clean, optimized code is easier to understand and maintain. Scalability: Efficient scripts handle larger workloads with minimal tweaks. Key Principles of Optimization 1. Avoid Useless Use of Commands Often, beginner scripts overuse commands unnecessarily. For instance: # Inefficient example cat file.txt | grep "pattern...

Advanced Bash Scripting: Unlock the Full Potential of Your Linux Shell

Image
Introduction Bash scripting is a cornerstone of Linux and Unix-based operating systems. While basic scripting helps with simple automation, advanced bash scripting empowers users to tackle complex tasks, manage system processes, and even build robust software solutions. This guide dives deep into advanced bash scripting, exploring its capabilities, practical examples, and techniques to make you a scripting expert. Why Learn Advanced Bash Scripting? Benefits of Advanced Bash Scripting Automation : Simplify repetitive tasks. Efficiency : Optimize system workflows. Powerful Tools : Combine tools like awk , sed , and grep for robust processing. Custom Solutions : Develop tailored scripts for specific needs. Applications System administration Data processing Web scraping File management DevOps and CI/CD pipelines Setting Up Your Environment Prerequisites Before diving into advanced techniques, ensure you have: A Unix-based OS (Linux, macOS, or WSL on Windows) Bash version 4.0 or higher (c...

Script Debugging in Shell: 7 Easy Fixes, Avoid Mistakes

Image
Script debugging in shell comes down to a few switches: set -x to see each command, bash -n to check the syntax, trap ... ERR to catch errors, and ShellCheck for static analysis. The old version of this post listed them with short examples. This rewrite runs every example in a Debian 13 container (GNU bash 5.2.37, dash, ShellCheck 0.10.0) and corrects what the output contradicts: the PS4 example, the ERR trap inside functions, the claim that bash -n finds errors, and an install command for a tool that is not in the repository. Contents Script debugging in shell with set -x and PS4 Use trap ERR for script debugging in shell, and know its limits What bash -n and bash -v really do in script debugging in shell Tracing without leaking secrets during script debugging in shell Script debugging in shell with ShellCheck and bashdb Common mistakes in script debugging in shell A practical order for script debugging in shell FAQ Script debugging in shell with set -x and PS4 The first exam...

Portable Shell Scripts: 7 Easy Rules to Avoid Errors

Image
Portable shell scripts are scripts that give the same result in every shell that may run them, not only in the Bash you wrote them in. The old version of this article listed general advice such as "use POSIX syntax" and "avoid system-specific tools" without showing a single failure. This rewrite runs the old snippets and 20 common Bash habits in six shells on Debian 13: dash (which is /bin/sh there), Bash 5.2.37, Bash in --posix mode, BusyBox sh, mksh R59 and posh, a shell that accepts only strict POSIX. ShellCheck then flags the same problems automatically. Contents What /bin/sh is: why portable shell scripts break The old examples: which ones were really portable shell scripts? Bash features that fail in portable shell scripts Let ShellCheck find the problems in portable shell scripts A short checklist for portable shell scripts FAQ What /bin/sh is: why portable shell scripts break The shebang #!/bin/sh does not mean Bash. In the lab container ls -l /bin/s...

Top Bash Scripts Every SysAdmin Should Know

Image
Introduction System administrators (sysadmins) are the backbone of any IT infrastructure. With responsibilities ranging from managing servers to troubleshooting network issues, time and efficiency are paramount. Enter Bash scripts —a powerful tool for automating repetitive tasks, enhancing productivity, and reducing human error. In this article, we explore the top Bash scripts every sysadmin should know , showcasing how they can streamline workflows and optimize system management. Essential Bash Scripts for Every SysAdmin 1. System Monitoring Scripts Monitoring system health is crucial for maintaining uptime and performance. These scripts help track resource usage, identify bottlenecks, and alert admins to potential issues. Example: CPU and Memory Usage Report #!/bin/bash echo "CPU and Memory Usage Report" echo "===========================" echo "CPU Usage:" top -b -n1 | grep "Cpu(s)" | awk '{print $2 + $4}' | xargs -I{} echo ...

Bash New Line: 7 Easy Fixes, Avoid Newline Mistakes

Image
Handling a bash new line sounds simple, until a file has no final newline or a script runs under sh . The old version of this post explained echo, printf and a few filters, and four of its statements are wrong in a real shell. This rewrite runs each example in Bash 5.2.37 on Debian 13 (and dash where it matters) and shows byte-level output with od -c and cat -A . Contents Bash new line with echo and printf Two claims about the bash new line that are wrong Multi-line variables and removing a bash new line Reading files with a bash new line: the last line and CRLF A helper that appends a bash new line safely Common mistakes with the bash new line Which tool to pick for a bash new line task FAQ Bash new line with echo and printf echo "Hello" printed the five letters and \n ; echo -n "Hello, World!" printed no newline at all. printf "Line 1\nLine 2\n" printed both lines with their newlines. So far the old text is right. The next claim is about variabl...