Run any shell script line by line: Show command before execution and wait for confirmation.

Jonas Felix
letsboot
Published in
2 min readJul 22, 2020
#!/bin/bash
trap 'read -p "run: $BASH_COMMAND"' DEBUG

As a trainer at letsboot.com I do a lot of walkthrough material. This statement helps me a lot in making interactive scripts for teaching anything in the command line. But it’s amazing for any shell script you want to DEBUG it.

Use this magic line at the beginning of any bash script if you want to:

  • Print the next command before it’s executed (similar to set -o xtrace or bash -x)
  • Wait for user input or confirmation (read) before executing the next command

Example:

As bash is providing the option -x or xtrace you may look for a similar option, to make it stop before every command, but there isn’t. The next thing you may find is the trap DEBUG statement which lets you run a script before each command. Combining those won’t work, as xtrace isn’t outputting anything before the actual command is run. So now finding the variables available in the trap function I used compgen -v (works only from within the trap function). I love and hate shell scripts, but at least I learn all the time.

Hint: If you have a loop like for, you’ll have to confirm on every iteration.

--

--

Jonas Felix
letsboot

Full Stack Entrepreneur - on a creative journey after first successful exit. New tech, science, OpenSource, Software Development, Space Enthusiast, Skydiver...