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

4
  • 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 Commented Jul 9, 2021 at 7: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. Commented Jul 9, 2021 at 7: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 unix.stackexchange.com/a/444949/198262 Commented Jul 9, 2021 at 8: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. Commented Jul 9, 2021 at 8:04

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
So you'll need an array I guess. Have another look above.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.