0

I am looking at how to generically print in the Bash script the command input which has failed.

So instead of:

date -q || { echo "date -q"; return 1; }

I would like to have in my script something like

date -q || { echo !!; return 1; }

or

date -q || { fc -ln -1; return 1; }

Then, I can use compactly always the same code to print the command input which has failed in the script.

However, both attempts above, echo !! and fc -ln -1, do not solve the problem

James Z
  • 12,209
  • 10
  • 24
  • 44
  • 1
    For `echo !!` to work you'd need `set -o history -o histexpand` but it can't work on the same line because the whole line is a command, you'd have to use a condition with `$?` in a separate line – CherryDT Jul 09 '21 at 07:56
  • Thanks for the quick feedback! I was hoping there is some built-in functionality in Bash to achieve this goal, e.g. $_ retrieves the last word of previous command input. I am looking for the solution along the same lines, some built-in shortcut but for the whole previous command input, not only for the last word. – user9751447 Jul 09 '21 at 07:56
  • 1
    (messed up my previous edit) - you can save the command in a variable and run&echo it from there, using `eval` or better an array, see https://unix.stackexchange.com/a/444949/198262 – CherryDT Jul 09 '21 at 08:00
  • This will work, but then I have to use it for each single command input in the cript. The net result is that my script will get longer, nor shorter, as intended. – user9751447 Jul 09 '21 at 08:04

1 Answers1

0

What do you mean by command input? Do you want the script to print the literal command if it returns a non-zero exit status? If so, you can do this:

comm="date -q"
eval "$comm" || {
    echo "Failed command: $comm"
    return 1
}

If you want to do this on multiple commands:

## create an array of commands
commands=(
    "date -q"
    "date -w"
    "date -e"
    "date -r"
)

## iterate over the commands
for command in "${commands[@]}"; do
    eval "$command" 2>/dev/null || echo "Failed: $command"
done
nino
  • 554
  • 2
  • 7
  • 20
  • Yes! Command and all its arguments. I seek an analogy to $_ which prints the last word of the previous command input, I just need something which prints the whole previous command input. – user9751447 Jul 09 '21 at 08:06
  • Thanks for the new post! This will work, but the problem if that I have to use it for each single command input in the script. The net result is that the script will get longer, and not shorter, as intended. – user9751447 Jul 09 '21 at 08:38
  • So you'll need an array I guess. Have another look above. – nino Jul 09 '21 at 09:37