Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.
pwd | grep 'database$'
if [ "$?" = 0 ]; then
echo "has db"
cd ..
cd ..
echo "after has db"
fi

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
add comment

2 Answers

up vote 11 down vote accepted

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

If you do:

sh ./script.sh

Or

./script.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:

. ./script.sh

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

share|improve this answer
2  
@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
add comment

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

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

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

share|improve this answer
add comment

Your Answer

 
discard

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.