LiLou1
LiLou1

Reputation: 31

How to save the return value of cd?

I have this:

cd $dir

if[ $? -eq 0 ]; then ...
else echo "The directory doesn't exist"; exit -1;
fi

And what I want is that if the cd returns an error (on the 1st line) the error won't be shown by the shell. I only want to be shown the message that I wrote. I tried to do:

ret=$(cd $dir)

But that doesn't work. How can I do it?

Upvotes: 0

Views: 2788

Answers (4)

William Pursell
William Pursell

Reputation: 212664

If the directory does exist, but the script does not have permission to enter it, then what you are trying to do is confuse the user. If your intent is to confuse the user, then go ahead and use the other answers provided. But what you really want to do is let cd emit the error message and just write:

cd $dir || exit 255

Trying to print an error message when you have absolutely no idea what error occurred just leads to confusion.

Upvotes: 2

jlliagre
jlliagre

Reputation: 30873

cd $dir 2>/dev/null || { echo "The directory doesn't exist"; exit -1; }
...

Upvotes: 1

SiegeX
SiegeX

Reputation: 140557

if cd $dir 2> /dev/null; then ...; else echo "The directory doesn't exist"; exit -1; fi

Upvotes: 4

hmjd
hmjd

Reputation: 122011

Redirect standard error:

cd $dir 2>/dev/null

Upvotes: 4

Related Questions