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

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

#!/bin/bash
cd /home/artemb

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


当前回答

我已经做了一个脚本来更改目录。来看看:https://github.com/ygpark/dj

其他回答

如果你正在使用bash,你可以尝试alias:

在.bashrc文件中添加这一行:

alias p='cd /home/serdar/my_new_folder/path/'

当你在命令行上写“p”时,它会改变目录。

鉴于答案的不可读性和过于复杂,我认为这是请求者应该做的

将该脚本添加到PATH 运行脚本。scriptname

的。(.)将确保脚本不在子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 /home/artemb

保存为:

echo cd /home/artemb

然后启动它:

\`./the_script\`

然后使用相同的shell访问该目录。

我还创建了一个名为goat的实用程序,您可以使用它来简化导航。

你可以在GitHub上查看源代码。

从v2.3.1开始,使用概述如下所示:

# Create a link (h4xdir) to a directory:
goat h4xdir ~/Documents/dev

# Follow a link to change a directory:
cd h4xdir

# Follow a link (and don't stop there!):
cd h4xdir/awesome-project

# Go up the filesystem tree with '...' (same as `cd ../../`):
cd ...

# List all your links:
goat list

# Delete a link (or more):
goat delete h4xdir lojban

# Delete all the links which point to directories with the given prefix:
goat deleteprefix $HOME/Documents

# Delete all saved links:
goat nuke

# Delete broken links:
goat fix