0

I'm using bash to execute complex scripts having for and wile loops. I activate the history in the script using :

set -o history -o histexpand

But if I execute the following script:

#!/bin/bash
set -o history -o histexpand
for i in 1 2 3 4 5
do
   echo "Welcome $i times"
done
history

I can see that 'history' does not track commands inside the for loop :

[scripts]$ ~/test2.sh
Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times
    1  for i in 1 2 3 4 5; do    echo "Welcome $i times"; done
    2  history

Is there a way to track the commands inside the for loop also ? In this present sample, I would love to get the following result :

[scripts]$ ~/test2.sh
Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times
    1  for i in 1 2 3 4 5; do    echo "Welcome $i times"; done
    2  echo "Welcome $i times"
    3  echo "Welcome $i times"
    4  echo "Welcome $i times"
    5  echo "Welcome $i times"
    6  echo "Welcome $i times"
    7  history
  • 2
    May I know your concern for doing this. do you want to track your script flow while executing? – msp9011 Sep 5 '18 at 11:05
  • Of course : I would like to display the last executed command when there is an error, event if the error was inside a loop of my script... – Richard Sep 5 '18 at 12:38
  • Because I'm not in development phase anymore and the script is executed every 5 minutes. and I would like to send by e-mail a functional error report, displaying the command that did not work... And this command work certainly 99% of the time... – Richard Sep 5 '18 at 13:16
1

The "history" is a history of "previously typed" commands.

From the GNU manual:

"When the -o history option to the set builtin is enabled ... the shell provides access to the command history, the list of commands previously typed."

So, it does neither substitute shell variables, nor does it save loop iterations.

For this you could use bash debugging by calling your script so:

bash -x myscript > to-my-log-file

Then, in case of a crash, you can see what happened in the log file (provided the system had had time to flush the output buffer).

  • ok, thank you for your answer. It was also my first analysis, but I asked the question in case someone had a workaround... – Richard Sep 5 '18 at 17:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.