Rodrigo
Rodrigo

Reputation: 12683

How execute bash script line by line?

If I enter bash -x option, it will show all the line. But the script will execute normally.

How can I execute line by line? Than I can see if it do the correct thing, or I abort and fix the bug. The same effect is put a read in every line.

Upvotes: 135

Views: 123253

Answers (5)

user647772
user647772

Reputation:

The BASH Debugger Project is "a source-code debugger for bash that follows the gdb command syntax."

Upvotes: 33

Tinmarino
Tinmarino

Reputation: 4041

xargs: can filter lines

cat .bashrc | xargs -0 -l -d \\n bash
  • -0 Treat as raw input (no escaping)
  • -l Separate each line (Not by default for performances)
  • -d \\n The line separator

Upvotes: 2

Brad Parks
Brad Parks

Reputation: 72001

If your bash script is really a bunch of one off commands that you want to run one by one, you could do something like this, which runs each command one by one when you increment a variable LN, corresponding to the line number you want to run. This allows you to just run the last command again super easy, and then you just increment the variable to go to the next command.

Assuming your commands are in a file "it.sh", run the following, one by one.

$ cat it.sh
echo "hi there"
date
ls -la /etc/passwd

$ $(LN=1 && cat it.sh | head -n$LN | tail -n1)
"hi there"

$ $(LN=2 && cat it.sh | head -n$LN | tail -n1)
Wed Feb 28 10:58:52 AST 2018

$ $(LN=3 && cat it.sh | head -n$LN | tail -n1)
-rw-r--r-- 1 root wheel 6774 Oct 2 21:29 /etc/passwd

Upvotes: 4

mug896
mug896

Reputation: 2025

Have a look at bash-stepping-xtrace.

It allows stepping xtrace.

Upvotes: 3

organic-mashup
organic-mashup

Reputation: 2138

You don't need to put a read in everyline, just add a trap like the following into your bash script, it has the effect you want, eg.

#!/usr/bin/env bash
set -x
trap read debug

< YOUR CODE HERE >

Works, just tested it with bash v4.2.8 and v3.2.25.


IMPROVED VERSION

If your script is reading content from files, the above listed will not work. A workaround could look like the following example.

#!/usr/bin/env bash
echo "Press CTRL+C to proceed."
trap "pkill -f 'sleep 1h'" INT
trap "set +x ; sleep 1h ; set -x" DEBUG

< YOUR CODE HERE >

To stop the script you would have to kill it from another shell in this case.


ALTERNATIVE1

If you simply want to wait a few seconds before proceeding to the next command in your script the following example could work for you.

#!/usr/bin/env bash
trap "set +x; sleep 5; set -x" DEBUG

< YOUR CODE HERE >

I'm adding set +x and set -x within the trap command to make the output more readable.

Upvotes: 173

Related Questions