Coding⏱️ 3 min read📅 2026-06-15

How to Fix: Get last command in error trap in zsh

Learn how to fix the last command in error trap for zsh shell.

Quick Answer: Use the $BASHPID variable instead of $_ to get the full command.

The 'Get last command in error trap in zsh' issue occurs when a user is unable to retrieve the last command executed before an error occurs within a script written in zsh. This can be frustrating for users as it prevents them from accurately tracing the cause of the error.

This issue affects users who rely on scripts to automate tasks and require precise control over their workflow. Fortunately, there are steps that can be taken to resolve this issue and improve the overall functionality of zsh scripts.

💡 Why You Are Getting This Error

  • The primary reason for this issue is the use of the 'TRAPZERR' function in zsh scripts, which only retrieves the last argument passed to it. This limitation makes it difficult to track down the exact command that caused an error.
  • Another possible cause is the lack of understanding about how to properly utilize the 'TRAPZERR' function and its limitations.

🚀 How to Resolve This Issue

Using the 'history' Command

  1. Step 1: To resolve this issue, users can use the built-in 'history' command in zsh to retrieve the last command executed before an error occurs.
  2. Step 2: Open a new terminal window and run the following command: 'history -n'. This will display the n-th most recent command in the history list.
  3. Step 3: By using the 'history' command, users can accurately track down the last command that was executed before an error occurred.

Modifying the 'TRAPZERR' Function

  1. Step 1: Alternatively, users can modify the 'TRAPZERR' function to retrieve all commands in the history list instead of just the last argument.
  2. Step 2: To do this, add the following line to the 'TRAPZERR' function: `cmd=${BASH_COMMAND}`. This will assign the value of ${BASH_COMMAND} to the variable 'cmd', which contains the entire command that was executed.
  3. Step 3: By modifying the 'TRAPZERR' function in this way, users can retrieve all commands in the history list and accurately track down the cause of errors.

🎯 Final Words

In conclusion, the 'Get last command in error trap in zsh' issue can be resolved by using either the built-in 'history' command or modifying the 'TRAPZERR' function to retrieve all commands in the history list. By following these steps, users can accurately track down errors and improve the overall functionality of their scripts.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions