Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display error and exit when cd exits with error

Tags:

bash

I want to let my script exit with a message when a cd command fails. I tried that by do the following:

cd $foo || echo "Error xyz"; exit 1

However, exit gets called regardless of the cd's success. When I type the following, it does not work either, because exit only exits the subshell:

cd $foo || ( echo "Error xyz"; exit 1 )

How can I achieve the desired behaviour without defining a function? Of course I could just compare $(pwd) with $foo, but that could lead to problems regarding symlinks and stuff.

like image 480
mfnalex Avatar asked Oct 31 '17 10:10

mfnalex


People also ask

How do I display exit status in last command?

The echo command is used to display the exit code for the last executed Fault Management command.

How do you exit a script if command fails?

Exit When Any Command Fails This can actually be done with a single line using the set builtin command with the -e option. Putting this at the top of a bash script will cause the script to exit if any commands return a non-zero exit code.

What is exit 2 in shell script?

Exit code 2 signifies invalid usage of some shell built-in command. Examples of built-in commands include alias, echo, and printf.

What is Pipefail in bash?

pipefail. If set, the return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands in the pipeline exit successfully. This option is disabled by default.


2 Answers

You can use the { list; } compound command. The list of commands is executed in the current shell context:

cd "$foo" || { echo "Error xyz"; exit 1; }

(Note the trailing semicolon or newline is required.)


The most common definition of functions in bash usually uses exactly this compound command for the "function body":

f() { list; }

although, bash functions can be defined with any compound command for their body, for example:

f() ( list; )
f() (( $1 > 10 ))
f() [[ $1 != "test" ]]

even:

f() for i in {1..10}; do echo $i; done
f() case ... esac
like image 163
randomir Avatar answered Sep 19 '22 03:09

randomir


You can just use an if statement. It is more readable in most cases, especially if you want to craft a proper error message:

if ! cd "${dir}" ; then
    echo "Failed to enter folder ${dir}"
    echo "Aborting"
    exit 1
fi
like image 45
hek2mgl Avatar answered Sep 19 '22 03:09

hek2mgl