Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
pwd | grep 'database$'
if [ "$?" = 0 ]; then
echo "has db"
cd ..
cd ..
echo "after has db"

after I execute it I see

has db
after has db

and I'm still in the same dir, how to fix it?

share|improve this question
up vote 11 down vote accepted

I think it has to do with how you run the script.

If you do:

sh ./



Then it invokes a new shell, runs the script, then returns you to the current one. So the cd is done in the new shell and your current one is untouched.

Try this instead:

. ./

Which will run in your current shell, and you'll keep the results after it finishes.

share|improve this answer
@UAdapter: to be sure that the issue is how u r running the script and not with the script, try printing the current working directory from the script before and after executing each cd command. – binW Nov 18 '11 at 16:59

A function would be more suitable for a command like this. E.g.

back() {
    if [[ $PWD = *database ]]; then
        cd ../../

Put it in ~/.bashrc to have this new back command available in new interactive bash sessions.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.