Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
990 views
in Technique[技术] by (71.8m points)

bash - How can I cd into a directory using a script?

For example, let's say I have a directory called tmp and I am on the home directory

$pwd
/my/home/directory/
$ls
tmpdir

and I have a tmp.sh that cds into the "tmp" directory

#!/bin/bash
cd tmp

and I run the script using:

$sh tmp.sh

after running this script, I am still in my home directory.

1) I want to understand why this doesn't work thoroughly(I just roughly know it has to do with children process that is independent of parent process(is this even right?)) and

2) how can I go about accomplishing this task(being end up in the directory that a script cd-ed in upon the completion of execution of the script)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That's the working directory of your shell. When you execute a script a new shell is created for your script. You are changing the present working directory for rest of your code and not the parent shell.

2) how can I go about accomplishing this task(being end up in the directory that a script cd-ed in upon the completion of execution of the script)?

To accomplish this you can && you script. So if the script executes successfully then only you end up in the new directory as

./tmp.sh && cd <to_your_directory>

You should also go through the unix.se post - Why cd is not a program? for better understanding.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...