如何在shell脚本中运行'cd'并在脚本完成后留在那里?

qrt*_*tt1 68 bash shell cd pwd

我在shell脚本中使用了'更改目录'(bash)

#!/bin/bash
alias mycd='cd some_place'
mycd
pwd
Run Code Online (Sandbox Code Playgroud)

pwd打印some_place正确,但脚本完成后,我当前的工作目录不会更改.

是否可以通过脚本更改我的路径?

cod*_*ict 80

您需要将文件作为源:

. myfile.sh
Run Code Online (Sandbox Code Playgroud)

要么

source myfile.sh
Run Code Online (Sandbox Code Playgroud)

如果没有源代码,则更改将在子shell中发生,而不是在调用脚本的父shell中发生.但是,当您获取文件时,文件中的行将被执行,就好像它们是在命令行中键入一样.


sch*_*hot 16

该脚本在单独的子shell中运行.子shell改变目录,而不是你运行它的shell.一个可能的解决方案是source脚本而不是运行它:

# Bash
source yourscript.sh
# or POSIX sh
. yourscript.sh
Run Code Online (Sandbox Code Playgroud)


tho*_*asd 14

在寻找您想要运行的脚本是一种解决方案时,您应该知道此脚本可以直接修改当前shell的环境.此外,不再能够传递参数.

另一种方法是将脚本实现为bash中的函数.

function cdbm() {
    cd whereever_you_want_to_go
     echo arguments to the functions were $1, $2, ...
}
Run Code Online (Sandbox Code Playgroud)

autojump使用此技术:http://github.com/joelthelion/autojump/wiki 为您提供学习shell目录书签.