是否可以从脚本更改当前目录?

我想在Bash中创建一个目录导航实用程序。我创建了一个测试脚本,如下所示:

#!/bin/bash
cd /home/artemb

当我从Bash shell执行脚本时,当前目录不会改变。是否有可能从脚本更改当前shell目录?


当前回答

使用pushd,当前目录被推送到目录堆栈上,并被更改为给定的目录,popd获取堆栈顶部的目录并更改为该目录。

pushd ../new/dir > /dev/null
# do something in ../new/dir
popd > /dev/null

其他回答

这种方法对我来说更容易。

假设在个人iMac上,你是管理员,当打开命令窗口时,在默认目录下/Users/jdoe,这将是进入的目录:/Users/jdoe/Desktop/Mongo/db.3.2.1/bin。

下面这些步骤可以帮助你完成工作:

vi mongobin,我进去了: cd /Users/jdoe/Desktop/Mongo/db.3.2.1/bin作为第一行。 Chmod 755 mongobin 源mongobin 松材线虫病

拖鞋!

如果您运行bash脚本,那么它将在其当前环境或其子环境上操作,而不会在父环境上操作。

如果目标是运行命令: goto.sh /home/test 然后在/home/test中交互式地工作,一种方法是在你的脚本中运行一个bash交互式子shell:

#!/bin/bash
cd $1
exec bash

这样,您将处于/home/test中,直到退出(退出或按Ctrl+C)这个shell。

你需要把你的脚本转换成一个shell函数:

#!/bin/bash
#
# this script should not be run directly,
# instead you need to source it from your .bashrc,
# by adding this line:
#   . ~/bin/myprog.sh
#

function myprog() {
  A=$1
  B=$2
  echo "aaa ${A} bbb ${B} ccc"
  cd /proc
}

原因是每个进程都有自己的当前目录,当您从shell执行一个程序时,它是在一个新进程中运行的。标准的“cd”,“pushd”和“popd”内置在shell解释器中,因此它们会影响shell进程。

通过使程序成为shell函数,您将添加自己的进程内命令,然后任何目录更改都会反映到shell进程中。

在你的shell脚本中添加以下cd行:

exec $SHELL

简单地去

yourusername/.bashrc (or yourusername/.bash_profile on MAC) by an editor

然后把下面的代码加到最后一行:

alias yourcommand="cd /the_path_you_wish"

然后退出编辑。

然后输入:

source ~/.bashrc or source ~/.bash_profile on MAC.

现在你可以在终端中使用:your命令