shell script show commands executed

Shell Script: Display Executed Commands

By Andrew Lewis
AD

When you run a complex series of commands in the terminal, it is easy to lose track of exactly what your shell script is doing at every moment. Understanding how to effectively monitor and audit these operations is essential for both debugging errors and ensuring reliable automation. This guide focuses on practical methods for a shell script show commands executed, helping you bring transparency to your background jobs and interactive sessions.

Many system administrators and developers rely on simple echo statements or manual logging, but there are more robust techniques available. You can leverage built-in shell features, external utilities, and clever redirection to create a comprehensive audit trail. The goal is to move beyond guesswork and implement a clear, searchable record of every step your script takes.

Enabling Execution Trace Features

The easiest way to see commands as they run is to activate the native tracing functionality provided by shells like Bash and Zsh. This feature prints each line to standard error before it is actually executed, acting like a real-time commentary of your script.

AD
Intro to Shell Scripts
Intro to Shell Scripts
All PowerShell Operators Explained
All PowerShell Operators Explained
a green background with the words trace exception commands in shell scripting and an image of a
a green background with the words trace exception commands in shell scripting and an image of a

Using this method is often the first line of defense when something goes wrong. It provides immediate context without requiring you to manually sprinkle print statements throughout your code. You can enable it temporarily or enforce it strictly to ensure no command runs unseen.

Using the Xtrace Option with Set

You can turn on tracing for the current session or a specific script by using the set -x command. Placing this at the top of your file right after the shebang ensures that every subsequent line is logged. To turn it off, you simply use set +x when the verbose output is no longer needed.

Linux Shell Scripting Command Cheat Sheet
Linux Shell Scripting Command Cheat Sheet
Shell Special Variables and Execution Environment
Shell Special Variables and Execution Environment
Linux Shell Scripting
Linux Shell Scripting

For instance, a script that starts with #!/bin/bash followed by set -x will print every command and its expanded arguments. This is extremely useful for debugging parameter expansion issues or verifying that loops are iterating over the correct file list.

Invoking Bash with the Verbose Flag

Alternatively, you can invoke the shell with the -v flag from the command line. This method tells the shell to print each line of the script *before* parsing, which is helpful for catching syntax errors or malformed scripts early.

AD

While -v reads the source code, -x prints the commands after variable expansion. Using both together provides the most detailed insight, ensuring you see exactly how the interpreter translates your script into actions.

Introduction to Linux Shell and Shell Scripting - GeeksforGeeks
Introduction to Linux Shell and Shell Scripting - GeeksforGeeks
Shell - A Command Line Interpreter
Shell - A Command Line Interpreter
How do I Check if a Directory or File exists in a Bash Shell Script?
How do I Check if a Directory or File exists in a Bash Shell Script?
How to Perform Syntax Checking Debugging Mode in Shell Scripts
How to Perform Syntax Checking Debugging Mode in Shell Scripts
How to Write a Shell Script in Ubuntu
How to Write a Shell Script in Ubuntu
Master Linux: Chain Commands with Logical Operators! 🐧
Master Linux: Chain Commands with Logical Operators! 🐧

Implementing Custom Logging Mechanisms

While tracing is powerful, sometimes you need a structured log file that captures the output of commands rather than just the commands themselves. Redirecting standard output and standard error to a file allows you to review results long after the terminal session has ended.

This approach is vital for unattended cron jobs or long-running data processing tasks. By appending timestamps and status messages, you can transform a simple log into a powerful diagnostic tool that shows the progression of your script over time.

AD

Redirecting Output to a Log File

A common pattern is to use > to capture standard output and 2>&1 to merge standard error into the same stream. By piping this combined stream to the tee command, you can write the output to a file while still displaying it on the screen for real-time monitoring.

🔄 Redirection, Pipe & Shell Script Basics in Linux
🔄 Redirection, Pipe & Shell Script Basics in Linux
How to Store or Assign a Linux command in a Variable in Bash Shell Script
How to Store or Assign a Linux command in a Variable in Bash Shell Script
Top 11 Resources to Learn Shell Scripting for Free
Top 11 Resources to Learn Shell Scripting for Free
What is shell scripting | How shell scripting works in Hindi / Urdu
What is shell scripting | How shell scripting works in Hindi / Urdu
Mastering bash String Operators and Arrays in UNIX Shells
Mastering bash String Operators and Arrays in UNIX Shells
20 Windows PowerShell Commands You Must Know
20 Windows PowerShell Commands You Must Know
Bash Scripting Tutorial – Linux Shell Script and Command Line for Beginners | digital daily
Bash Scripting Tutorial – Linux Shell Script and Command Line for Beginners | digital daily
Automate Your Wordpress Backup With Simple Shell Scripting & CRON
Automate Your Wordpress Backup With Simple Shell Scripting & CRON
Bash scripting cheatsheet
Bash scripting cheatsheet
Google engineers explain the backdoor script installed in the compression tool 'XZ Utils' used in Linux environments
Google engineers explain the backdoor script installed in the compression tool 'XZ Utils' used in Linux environments
UNIX Shell Scripting Tutorial - The Basics for Beginners...and Beyond!!!
UNIX Shell Scripting Tutorial - The Basics for Beginners...and Beyond!!!
Client Challenge
Client Challenge
How To Write Shell Scripts in Node with Google’s zx Library
How To Write Shell Scripts in Node with Google’s zx Library
Shell Scripting: How to Automate Command Line Tasks Using Bash Scripting and Shell Programming
Shell Scripting: How to Automate Command Line Tasks Using Bash Scripting and Shell Programming

This technique ensures that you never lose critical error messages, even if you are running the script over an unstable SSH connection. The log file acts as a persistent record that you can grep through to find specific failure points.

Adding Timestamps for Better Context

Raw logs are useful, but adding timestamps takes your debugging capabilities to the next level. You can create a custom function that prefixes every line with the current date and time, allowing you to measure the duration between steps and correlate events across multiple systems.

AD

By integrating this with your logging redirection, you create a detailed timeline of execution. This is particularly valuable when a script fails intermittently, as the timestamps can reveal delays or race conditions that are otherwise invisible.

Advanced Process Monitoring Tools

For system-level visibility, you can utilize powerful tools that monitor processes outside of the shell script itself. These utilities provide a view of resource usage, open files, and system calls, which is essential for performance optimization.

Using these tools in conjunction with your logging strategy gives you a holistic view of the script's behavior. You can see not only what commands are running but also how much CPU and memory they consume.

Utilizing Strace for System Calls

The strace command is a debugger that intercepts and records the system calls made by a process. By running your script with strace, you can see every interaction it has with the kernel, such as file reads, network connections, and memory allocations.

This level of detail is indispensable when you suspect permission issues or hanging file locks. It allows you to verify that your script is accessing the exact files and sockets you expect it to.

Leveraging top and htop for Resource Usage

While strace shows internal behavior, tools like top and htop provide a high-level view of system resource consumption. You can use these to monitor the CPU and memory footprint of your shell script in real time.

Watching these metrics helps you identify bottlenecks. If a script is consuming 100% of the CPU, you know the issue is computational, whereas high memory usage might indicate a problem with data buffering or variable storage.

Best Practices and Maintenance Tips

To ensure your methods for tracking command execution remain effective, it is important to follow consistent conventions. Naming your log files with dates and script versions prevents confusion and makes archiving straightforward.

Moreover, be mindful of log verbosity. While it is tempting to log everything, excessive noise can make it difficult to spot the critical error messages. Striking a balance between detail and clarity is key to maintaining a useful audit trail.

Finally, always test your tracing and logging setup in a safe environment before deploying it to production. A script that is difficult to read due to excessive debug output can defeat the purpose of observability. Keep your logs clean, structured, and focused on the data that actually helps you solve problems.

By combining built-in shell options with smart redirection and system monitoring, you can achieve complete transparency into your automation workflows. This disciplined approach not only speeds up troubleshooting but also builds confidence in the reliability of your scripts over time.

AD