zsh -x but don't show the full path

Viewed 341

Let's assume I have a script:

$ cat script.sh
#!/usr/bin/env zsh
myfunc() {
    echo Hello
}
uptime
myfunc

And I run it with zsh -x $PWD/script.sh, I get the following output:

$ zsh -x $PWD/script.sh
+/Users/username/.zshenv:8> [[ 2 -eq 1 ]]
+/Users/username/so/script.sh:5> uptime
20:12  up 2 days,  1:04, 7 users, load averages: 4.09 3.65 3.42
+/Users/username/so/script.sh:6> myfunc
+myfunc:1> echo Hello
Hello

I would prefer that instead of printing the full path to the script, just the basename are used, similarly to how the function name is shown. Desired output:

$ zsh -x $PWD/script.sh
+.zshenv:8> [[ 2 -eq 1 ]]
+script.sh:5> uptime
20:12  up 2 days,  1:04, 7 users, load averages: 4.09 3.65 3.42
+script.sh:6> myfunc
+myfunc:1> echo Hello
Hello

I know I can cause this to happen by doing e.g. zsh -x myscript and not providing the full path, but lots of scripts are run by their full path, when they are in $PATH. Often I debug scripts via zsh -x =scriptname where the = modifier causes the full path to be expanded.

Are there any set options, environment variables, or additional flags that I can pass such that zsh -x only shows the basename of the script? Or any additional way to customize the output of zsh -x would be really useful.

1 Answers

The value printed out when using zsh -x (also known as the option XTRACE) takes a format specifier from the environment variable $PS4. The documentation on ZSH options states:

XTRACE (-x, ksh: -x) Print commands and their arguments as they are executed. The output is preceded by the value of $PS4, formatted as described in Prompt Expansion.

It looks like your PS4='+%N:%i> '

There are many prompt expansion variables you can use, and you can find them in the Prompt Expansion documentation.

To get the result you want, you need to set e.g.:

$ export PS4="+%1N:%i> "
# or
$ export PS4="+%1N:%I> "

The former keeps the default line number behavior, but the latter shows the actual line numbers of the function being executed, which I find very useful. Instead of showing myfunc:1 it would show myfunc:3 since it's line 3 of the file that contains myfunc.

The output would then look like:

$ zsh -x $PWD/script.sh
+.zshenv:8> [[ 2 -eq 1 ]]
+script.sh:5> uptime
20:25  up 2 days,  1:17, 7 users, load averages: 3.22 3.58 3.49
+script.sh:6> myfunc
+myfunc:3> echo Hello
Hello
Related