我怎样才能cd进入使用脚本目录? [英] How can I cd into a directory using a script?

查看:141
本文介绍了我怎样才能cd进入使用脚本目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,假设我有一个名为tmp目录,我的主目录

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

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

和我有一个tmp.sh的CDS进入TMP目录

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

#!/bin/bash
cd tmp

和我使用运行脚本:

$sh tmp.sh

运行此脚本后,我仍然在我的主目录。

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

1),我想知道为什么,这并不摸底工作(我只大致知道它有带小孩的过程,是独立于父进程做(这是甚至对不对?))

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),我该怎么去完成这个任务(即在目录中结束,一个脚本CD-ED在脚本执行)完成后?

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)?

推荐答案

这是你的shell的工作目录。当你执行一个脚本,为您的脚本创建一个新的外壳。您正在改变present您code的休息,而不是父shell的工作目录。

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),我该怎么去完成这个任务(即在目录中结束,一个脚本CD-ED在脚本执行)完成后?

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>

您也应该通过unix.se后 - 为什么CD不是一个程序以更好地理解

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

这篇关于我怎样才能cd进入使用脚本目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆