更改目录“cd”使用bash
我想使用 bash 文件更改 Linux 中的目录。下面是使用的代码片段。
#!/bin/bash
alias proj="cd /home/prag/Downloads"
但是在运行 bash 文件时没有响应,即它保留在同一目录中。为什么会这样.?为什么别名在这里不起作用或者我应该做一些不同的事情?
I want to change the directory in linux using bash file. Below is the code snippet used.
#!/bin/bash
alias proj="cd /home/prag/Downloads"
But on running the bash file there is not response, i.e. it stays in the same directory. Why is it so.? Why doesn't alias work here or should I do something different.?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
运行 bash 文件将不起作用,因为对当前工作目录的更改保留在脚本内(因为它是为您提供命令提示符的进程 - bash 的一个单独的进程)。
将别名添加到您的 ~/.bash_aliases 或 ~/.bashrc 文件中(前者更好,如果前者不存在,后者可能会更快),然后它应该可以工作。
Running the bash file won't work as the change to the current working directory stays within the script (as it is a separate process to the process that gives you your command prompt - bash).
Add the alias to your ~/.bash_aliases or ~/.bashrc file (former is preferable, latter might be quicker if the former doesn't exist) and then it should work.
每个进程都有自己的当前目录。当您启动 bash 脚本,并且它更改其当前目录然后存在时,这对父进程(即您启动脚本的 shell)没有影响。
不要运行
./script.sh
,而是尝试source ./script.sh
(或简称为. ./script.sh
)。此外,为
cd
定义别名
本身不会更改目录。我假设您实际上在某处调用了别名。Each process has its own current directory. When you start a bash script, and it changes its current directory and then exists, this has no effect on the parent process (i.e. the shell from which you launches the script).
Instead of running
./script.sh
, trysource ./script.sh
(or. ./script.sh
for short).Also, defining an
alias
forcd
won't on its own change the directory. I assume you actually invoke the alias somewhere.你是说你想写一个 bash 脚本来 cd 到另一个目录吗?
那为什么要使用别名呢?只需使用“cd”命令即可!
Are you saying you want to write a bash script that will cd to another directory?
Then why use an alias? Just use the "cd" command!
这是因为当您像
./cd.sh
那样调用脚本时,它会在新的 shell 进程中执行。因此,您的脚本将更改该子 shell 中的目录,并且当您的脚本退出时,控制权将返回到之前的 shell。
您可以像
那样调用您的脚本。 cd.sh
- 这会在当前 shell 中执行脚本并且 cd 命令起作用。It is because your script is executed in a new shell-process when you call it like
./cd.sh
.So your script would change the directory in that subshell, and when your script exits control returns to your previous shell.
You can call your script like that
. cd.sh
- this executes the script in the current shell and the cd-command works.