是否可以从脚本更改当前目录?
我想在Bash中创建一个目录导航实用程序。我创建了一个测试脚本,如下所示:
#!/bin/bash
cd /home/artemb
当我从Bash shell执行脚本时,当前目录不会改变。是否有可能从脚本更改当前shell目录?
是否可以从脚本更改当前目录?
我想在Bash中创建一个目录导航实用程序。我创建了一个测试脚本,如下所示:
#!/bin/bash
cd /home/artemb
当我从Bash shell执行脚本时,当前目录不会改变。是否有可能从脚本更改当前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命令
其他回答
简单地去
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命令
鉴于答案的不可读性和过于复杂,我认为这是请求者应该做的
将该脚本添加到PATH 运行脚本。scriptname
的。(.)将确保脚本不在子shell中运行。
这是以上答案的一个简化汇编。 创建shell文件shell .sh 在脚本中,在函数中更改目录
#!/bin/bash
cd folder1/folder2/
现在运行脚本。在这之前。 . 使用当前线程/会话执行脚本。
. shellfile.sh
使用pushd,当前目录被推送到目录堆栈上,并被更改为给定的目录,popd获取堆栈顶部的目录并更改为该目录。
pushd ../new/dir > /dev/null
# do something in ../new/dir
popd > /dev/null
声明你的路径:
PATH='/home/artemb'
cd ${PATH}