Discussion:
[Help-bash] Usage of $BASH_COMMAND inside an auto retry function? Is there an expanded $BASH_COMMAND?
Patrick Schleizer
2017-03-10 01:25:00 UTC
Permalink
Hi,

I am using $BASH_COMMAND in a build script inside an ERR trap to
implement auto retry. (Some stuff temporarily fails due to network
issues but works on second attempt.)

Two things do not work well with $BASH_COMMAND.

a) When the last command contained variables. I.e.

some_variable="--some-switch"
apt-get $some_variable

Then BASH_COMMAND would just contain 'apt-get' but not '--some-switch'.
Is there an expanded variable similar to BASH_COMMAND that would hold
'apt-get --some-switch'?

b) Will not be possible to repeat a failed pipe command. For example:
echo something | apt-get

Then BASH_COMMAND will hold only 'apt-get'. Is there a variable that
holds the full command 'echo something | apt-get' so it cold be retried?

I guess alternatively I could use a loop that counts to two or three and
then `break`s. However, I don't really like that, since that complicates
the code. A general purpose ERR trap that has a auto retry feature seems
much nicer.

Another alternative would be to add a wrapper function in front of each
command that should be tried to auto retry. That would work, but would
also not look as clean.

That is why I am asking if it is sensible to use $BASH_COMMAND inside an
auto retry function or if there is there an expanded $BASH_COMMAND.

Cheers,
Patrick
Chet Ramey
2017-03-15 01:14:38 UTC
Permalink
Post by Patrick Schleizer
Hi,
I am using $BASH_COMMAND in a build script inside an ERR trap to
implement auto retry. (Some stuff temporarily fails due to network
issues but works on second attempt.)
Two things do not work well with $BASH_COMMAND.
a) When the last command contained variables. I.e.
some_variable="--some-switch"
apt-get $some_variable
Then BASH_COMMAND would just contain 'apt-get' but not '--some-switch'.
Is there an expanded variable similar to BASH_COMMAND that would hold
'apt-get --some-switch'?
More precisely, it gets "apt-get $some_variable". There is no variable
that holds the command after it's been expanded. You can always run the
value through "eval" but you should be prepared to deal with any
command substitutions or process substitutions that would be expanded.
Post by Patrick Schleizer
echo something | apt-get
Then BASH_COMMAND will hold only 'apt-get'. Is there a variable that
holds the full command 'echo something | apt-get' so it cold be retried?
`apt-get' is the last command executed, so that's what ends up in
BASH_COMMAND.

You might be able to look at the last history entry if you enable history
in your script.
--
``The lyf so short, the craft so long to lerne.'' - Chaucer
``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU ***@case.edu http://cnswww.cns.cwru.edu/~chet/
Loading...