为什么此脚本不更改目录 [英] Why is this script not changing directory

查看:54
本文介绍了为什么此脚本不更改目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定简单的bash脚本问题-不要笑.我的脚本只是更改目录:

Ok simple bash script question - don't laugh. My script just changes directory:

echo on;
echo "running script";
CURRENT_DIR=.;
cd ..;
pwd;

我可以在回显中看到它更改目录,但是完成后,我的终端仍在同一目录中.有提示吗?

I can see it change directory in the echo but when it finishes it, my terminal is still at the same directory. Any tips?

推荐答案

运行 bash 脚本时,该脚本在其自己的shell中运行.这意味着它具有自己的外壳环境,包括当前的工作目录.如果在脚本中 cd ,该脚本将在该新的当前目录中运行.但是,完成后,由于子外壳程序没有碰到它,因此您仍处于用户级外壳程序所在的当前目录中.

When you run a bash script, it runs in its own shell. That means that it has it's own shell environment including what the current working directory is. If you cd within the script, that script will be operating in that new current directory. But when it's completed, you are still at the current directory that your user-level shell is at since a subshell doesn't touch it.

如果要影响当前的shell环境,一种方法是使用.:

If you want to impact the current shell environment, one way is to execute it with .:

. my_script

这类似于运行 sh my_script ,但在当前用户外壳程序的环境中运行.

This is like running sh my_script but operates within the environment of your current user shell.

这篇关于为什么此脚本不更改目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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