eval: $? vs ${PIPESTATUS[@]} (bash)

 In Bash, `?` and `${PIPESTATUS[@]}` are used to check the exit status of commands, particularly in the context of pipelines.


1. `?`:

   - `$?` is a special variable that stores the exit status of the last executed command.

   - It's primarily used to check the success or failure of the most recently executed command.

   - For example, you can use it like this:

     ```bash

     some_command

     if [ $? -eq 0 ]; then

         echo "Command was successful."

     else

         echo "Command failed."

     fi

     ```


2. `${PIPESTATUS[@]}`:

   - `${PIPESTATUS[@]}` is an array that stores the exit statuses of all commands in a pipeline.

   - It is particularly useful when you have a series of commands piped together, and you want to check the exit status of each command in the pipeline.

   - For example:

     ```bash

     command1 | command2 | command3

     exit_statuses=("${PIPESTATUS[@]}")

     # Check the exit status of each command

     if [ ${exit_statuses[0]} -eq 0 ]; then

         echo "Command1 was successful."

     else

         echo "Command1 failed."

     fi

     if [ ${exit_statuses[1]} -eq 0 ]; then

         echo "Command2 was successful."

     else

         echo "Command2 failed."

     fi

     if [ ${exit_statuses[2]} -eq 0 ]; then

         echo "Command3 was successful."

     else

         echo "Command3 failed."

     fi

     ```


Using `${PIPESTATUS[@]}` is particularly useful in scenarios where you need to handle the exit status of each command in a pipeline separately. `?` is typically used for the most recent command and may not be as useful when dealing with complex pipelines.

Comments

Popular posts from this blog

bad character U+002D '-' in my helm template

GitLab pipeline stopped working with invalid yaml error

How do I add a printer in OpenSUSE which is being shared by a CUPS print server?