Verbose Mode
Returning to line 3 of the shim code:
[ -n $RBENV_DEBUG
] && set -x
If the [ -n
condition returns $RBENV_DEBUG
]true
, the &&
syntax ensures that we then execute the 2nd half of this line of code: set -x
. If that condition returns false, we exit early and don't evaluate set -x
.
We know about set
already, but what does the -x
flag do?
I don't see anything helpful when searching the output of man set
or help set
, so I refer back to the table of flags for set
which I first found when looking up the meaning of -e
:
Abbreviation | Name | Effect |
---|---|---|
-v | verbose | Print each command to stdout before executing it |
-x | xtrace | Similar to -v, but expands commands |
The description for -x
says "Similar to -v, but expands commands". In turn, the description for -v
says "Print each command to stdout before executing it". Based on this, it sounds like we're setting our shell to "debug mode". Which would make sense, given the 2nd half of the condition only executes if we've set a variable named RBENV_DEBUG
.
Let's see what that looks like.
Experiment- the set -x
command
I edit my foo
script to contain the following code:
#!/usr/bin/env bash
set -x
echo "foo"
echo "bar"
As you can see, this script includes set -x
at the top.
When I run this script, I see the following:
$ ./foo
+ echo foo
foo
+ echo bar
bar
$
The lines with +
in front of them appear to be the lines which are printed out as a result of set -x
. They show the code that gets executed, before that code is actually run.
In contrast, the lines without +
are lines that would have printed out anyway (i.e. as a result of the echo
commands I included in the script).
When I comment out set -x
and re-run the script, I see:
$ ./foo
foo
bar
$
Now we don't see the lines beginning with +
anymore. We just see the printed output from the executed code.
From this, we can conclude that set -x
prints each line of code that is run, just as our docs described.
So to summarize, line 3 of the shim file tells us that we will print each command as it is executed, but only if we set the $RBENV_DEBUG
environment variable to equal any non-empty string value.
Wrapping Up
Verbose mode is useful if you want to see which lines of code get executed just before an error occurs. To make full use of this, set -x
can be used in conjunction with set -e
, so that an exception is raised and the program immediately exits. This makes it easier to zero in on where the error occurred- just scroll to the end of the output, and look for the output of set -x
which occurs just before the output of the exception.
Let's move on to the next line of code.