Skip to content

Welcome to Tech by Example

Menu
  • Home
  • Posts
  • System Design Questions
Menu

How to handle failure in a command in bash or terminal

Posted on August 7, 2021August 7, 2021 by admin

Overview

In case the failure of the command should not stop the execution of the program,  then the below way can be used. 

command && echo "Success" || echo "Failure"
  • If the command fails then the output will be “Success”.
  • If the command above passed then the output will be “Failure”

Example

  • Success Case

In the example below the command is ‘pwd’ which is a valid command

export command=pwd
$command && echo "Success" || echo "Failure"

Output

{It will print the current directory}
Success
  • Failure Case

In the example below the command is ‘pwdd’ which is an invalid command

export command=pwdd
$command && echo "Success" || echo "Failure"

Output

-bash: pwdd: command not found
Failure

It prints Failure as pwdd is an invalid command

  • bash
  • linux
  • terminal
  • ©2025 Welcome to Tech by Example | Design: Newspaperly WordPress Theme