mtk*_*mtk 1 shell directory cd-command shell-script
可能重复:
使用脚本更改当前工作目录
我正在尝试创建一些脚本来更改主 shell/终端的工作目录。不能这样做。我尝试了以下
#!/bin/bash
cd /home/mtk/work/project1
Run Code Online (Sandbox Code Playgroud)
#!/bin/bash
cd /home/mtk/templates/resusable/sampleCodes
Run Code Online (Sandbox Code Playgroud)
但我知道,上面要改变它只是为自己,即在一个正在运行,这将是p1.sh或者code.sh在这种情况下。
请让我知道,我如何才能更改父调用 shell 的当前工作目录。
$ pwd
/home/mtk
$ p1.sh
$ pwd
/home/mtk ### --> Expected /home/mtk/work/project1
Run Code Online (Sandbox Code Playgroud)
我的用例是:我想做一些处理,然后将提示放置到预定义的目录中。
我明白为什么它不起作用。并且alias似乎是这种情况的解决方案。但我想扩大,我的问题:
我需要创建一个脚本来动态更改父 shell 的工作目录。脚本会说mycd.sh。它将具有命令行参数
mycd.sh -c/-p1/-p2/或其他一些用户定义的参数。
给予-c会将 shell 工作目录切换到相应的目录。文件mycd.sh看起来像
.. some processing
# parameter parsing
if [ $param1 -eq "c" ]; then
# change working dir of parent here
else
... other conditions
Run Code Online (Sandbox Code Playgroud)
我想,必须有某种方法可以更改 shell 工作目录。
如果有什么不清楚,请告诉我。
为此使用别名,例如
alias p1='cd /home/mtk/work/project1'
alias code='cd /home/mtk/templates/resusable/sampleCodes'
Run Code Online (Sandbox Code Playgroud)
您应该将这些行放入 shell 的启动脚本中,例如 ~/.bashrc.
另一种选择是使用shell 函数。这有点复杂;shell 函数提供了一些优于别名的优势,但在这种情况下,您不需要这些额外的功能。
function p1 { cd /home/mtk/work/project1; }
function code { cd /home/mtk/templates/resusable/sampleCodes; }
Run Code Online (Sandbox Code Playgroud)