If Error then Exit

HI

I am just using cd Command and i want exit if error.

Ex.

cd /hp/pp/0720

If above folder in not available then stop the script

Folder is change every day

Thanks

cd returns - like every other command - an error level you can use: it is stored in the variable "$?", which is updated after every executed command.

A return value of "0" (also: logical TRUE) means success, while values between 1 and 254 (all of them meaning a logical FALSE) show various error conditions.

You can use this in scripts in the following two ways:

command
if [ $? -eq 0 ] ; then
     echo "success"
else
     echo "some error occurred"
fi
command && echo "error occurred"

The second variant uses the logical meaning of non-zero being FALSE, the "&&" is a logical "OR": that way, if "command" returns "FALSE", the second command is executed, otherwise not.

I hope this helps.

bakunin

1 Like

or even

if command; then
...
fi
1 Like

I think "&&" is the logical "AND", "||" means "OR", so it should be

 command || echo "error occurred"
1 Like