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.

I know there is a simple command for this, but I'm trying to run a file.sh, which contains lines like:

mkdir $filename
cd $filename

the file executes, but ends in the file i began in. I know there is a simple keyword to put in front to make the execution leave me in the directory $filename, but i cant find it on the internet. I found it once before, but cant seem to do it again.

share|improve this question
add comment

2 Answers

According to this:

http://stackoverflow.com/questions/255414/why-doesnt-cd-work-in-a-bash-shell-script

you can run your script using

. ./scriptname

and it will run the shell script with your shell, not invoking a subshell like what usually happens.

share|improve this answer
2  
take care of replacing any "exit ..." by "return ..." otherwise it will exit the invoking shell, ie the one you typed the . ./scriptname in, closing it. –  Olivier Dulac Jan 29 '13 at 11:02
add comment

When you execute a shell script, it is equivalent of running it in an different shell. Doing ./script.sh is equal to sh script.sh, which may open the problem better for you.

To run the script in current shell context, you need to use source or its alias ., ie source script.sh or . script.sh.

Easiest solution for simple operation like this would be to create an alias instead of a script, ie. alias mkcd='mkdir dir; cd dir' or if you need to run arbitrary directories, you can do mkcd() { mkdir $1; cd $1 } function. You can put either of these into your ~/.bashrc or ~/.bash_aliases.

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.