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

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

#!/bin/bash
cd /home/artemb

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


当前回答

这是以上答案的一个简化汇编。 创建shell文件shell .sh 在脚本中,在函数中更改目录

#!/bin/bash

cd folder1/folder2/

现在运行脚本。在这之前。 . 使用当前线程/会话执行脚本。

. shellfile.sh

其他回答

把上面的内容放在一起,就可以创建一个别名

alias your_cmd=". your_cmd"

如果你不想每次都写开头的"." 你想把你的脚本源到shell环境, 或者如果你只是不想记住,那就必须这么做 脚本才能正确工作。

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

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

#!/bin/bash
cd $1
exec bash

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

我喜欢为不同的项目做同样的事情,而不需要启动新的shell。

在你的情况下:

cd /home/artemb

保存为:

echo cd /home/artemb

然后启动它:

\`./the_script\`

然后使用相同的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命令

我还创建了一个名为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