How can I separate the output for each command generated by the bash file?
Let's say we have a bash script like the one below:
echo test
ls -alh
pwd
echo test2
Thus, a file can contain any number of commands, each of which produces or does not output its own output.
Then the above file is run like this /bin/bash -xe test.sh
, which produces the following output:
+ echo test
test
+ ls -alh
total 32
drwx------+ 6 daniels staff 204B Apr 3 23:33 .
drwxr-xr-x+ 64 daniels staff 2.1K Apr 4 01:53 ..
-rw-r--r--@ 1 daniels staff 6.0K Apr 3 23:33 .DS_Store
drwxr-xr-x 5 daniels staff 170B Mar 15 17:03 Todo
-rw-r--r--@ 1 daniels staff 282B Apr 3 20:39 test.py
-rw-r--r--@ 1 daniels staff 97B Apr 4 01:52 test.sh
+ pwd
/Users/daniels/Desktop
+ echo test2
test2
Is there a reliable way to parse the generated output and figure out how to separate the output based on each command?
In the above example, we can split and extract one group:
+ echo test
test
another with
+ ls -alh
total 32
drwx------+ 6 daniels staff 204B Apr 3 23:33 .
drwxr-xr-x+ 64 daniels staff 2.1K Apr 4 01:53 ..
-rw-r--r--@ 1 daniels staff 6.0K Apr 3 23:33 .DS_Store
drwxr-xr-x 5 daniels staff 170B Mar 15 17:03 Todo
-rw-r--r--@ 1 daniels staff 282B Apr 3 20:39 test.py
-rw-r--r--@ 1 daniels staff 97B Apr 4 01:52 test.sh
and etc.
I was thinking to parse the output and see if the line starts with +
and then count that as the start of a single command, but then you can easily echo + ok
end up with something like causing this logic to fail.
Another option would be if we could change the char that is output /bin/bash -x
to instead of + output something like https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text , but looks like it's +
hardcoded in bash and not configurable.
Any ideas?
+
is not hardcoded and it is easily described in man bash
and under help set
for -x
:
-x After expanding each simple command, for command,
case command, select command, or arithmetic for
command, display the expanded value of PS4, fol‐
lowed by the command and its expanded arguments or
associated word list.
And here's a further description of the PS4, also from man bash
:
PS4 The value of this parameter is expanded as with PS1 and
the value is printed before each command bash displays
during an execution trace. The first character of PS4 is
replicated multiple times, as necessary, to indicate mul‐
tiple levels of indirection. The default is ``+ ''.
Here's an example:
$ PS4=$'\nAnd now, a word from '; set -x; date; uptime
And now, a word from date
Mon Apr 3 16:20:35 PDT 2017
And now, a word from uptime
16:20:35 up 65 days, 1:24, 6 users, load average: 1.20, 1.42, 1.37
You can use this to insert special markers or symbols as you like.