These variables describe the prompt itself:
PS1_Error="\[\033[31;1m\]"
PS1_Normal="\[\033[0m\]"
PS1_Inside='${debian_chroot:+($debian_chroot)}\u@\h:\w$bad\$ '
The colors are done using ANSI escape codes. \033
is the escape character (33 = 27 octal), then [31;1m
sets text color 31 and effect 1. [0m
sets effect 0, i.e. all default. Note how PS1_Inside
is in single quotes (''
), this means variable substitution is not performed at this step. (It will happen later.)
The real magic happens here:
PS1="\`
...
\`"
This sets PS1 to the output of executing the code within the ``
characters. Variable expansion will happen to whatever comes out. The code will run every time the prompt is shown. The code itself runs like so:
retcode=\$? ;
$?
contains the result of the previous command. Zero means OK, anything else is a fail condition. This is stored in retcode
for the time being. Everything needs to be escaped, because we want variables to be accessed when the code runs, not substituted at the time of definition.
if [ 0 -ne \$retcode ]; then
If it is not zero, something went wrong. So we echo the prompt style used for errors. bad
is used in PS1_Inside
above. PS1_Error
is used to change the color, PS1_Normal
is used to change the color back to normal.
bad=\" [\\\\\\\$?=\$retcode]\"
echo \"$PS1_Error$PS1_Inside$PS1_Normal\"
else
In this case, no error occurred, so we don't do any colors and just output PS1_Inside
. bad
is set to empty, so nothing will show up in the prompt.
bad='';
echo \"$PS1_Inside\";
fi;
Finally, the helper variables are unset so as not to clutter up the environment.
unset PS1_Error PS1_Normal PS1_Inside
Best Answer
One way to accomplish this is through indirection -- referring to another variable from the value of the first variable.
To demonstrate:
Results in:
Because bash first takes
!var
to mean the value of thevar
variable, which is then interpreted via${apple}
and turned intoRed
.As a result, your GetFruitColour.sh script could look like:
I've made the path to the sourced script relative instead of bare, to make it clearer where the file is (if the given filename does not contain a slash, shells will search the
$PATH
variable for it, which may surprise you).I've also changed
echo
toprintf
.The functional change is to use the looping variable
$arg
and the indirect expansion of it to produce the desired values:Do note that there's no error-checking here:
You may find it easier to use an associative array: