1

When chaining commands in zsh using ;, && and ||, how can I access the previous command in chain (the command that is being executed before)? Example:

rm foo ; echo ...

In place of the dots, I'm looking for some kind of command / variable that provides me with rm foo.

I have tried playing around a bit with history and !!, but those only provide the commands up until the command that was executed last, not the current one. Another idea was to use $0, but this only prints the location of zsh.

Accessing the complete chain would also be fine, if retrieving only the last command is not possible.

6
  • if you just want to enable printing of the commands executed, that can be implemented differently! May 31 at 9:02
  • @MarcusMüller I want to pass the command to another command down the line, specifically I want to use ntfy to send a notification with the command and status
    – josh
    May 31 at 9:34
  • 1
    that sounds a lot like you'd architecturally should rather write a function that takes the command as argument, executes and saves it for later (or logs it right away?), rather than trying to retrieve it after the fact! May 31 at 9:41
  • @MarcusMüller I thought that it would be good for ease of use to just have an alias that I can put at the end of a command, and then it takes care of notifying me. A function would be my alternative if this doesn't work out
    – josh
    May 31 at 10:42
  • I'd say it's a bit surprising to put something after something, when you actually want to apply it as an operation on it! In languages like shell languages, you typically have "function arguments..." not "arguments; function". May 31 at 10:44

1 Answer 1

0

You could do something like:

$ TRAPDEBUG() last_command=$current_command current_command=$ZSH_DEBUG_CMD
$ echo test; print -r -- $last_command
test
echo test

Beware there will be some reformatting of the commands:

$ (echo test); print -r -- $last_command
test
(
        echo test
)
$ (for a (1 2) echo $a); print -r -- $last_command
1
2
(
        for a in 1 2
        do
                echo $a
        done
)

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.