简体   繁体   English

使用bash更改目录'cd'

[英]Changing directory 'cd' using bash

I want to change the directory in linux using bash file. 我想使用bash文件更改linux中的目录。 Below is the code snippet used. 以下是使用的代码段。

#!/bin/bash
alias proj="cd /home/prag/Downloads"

But on running the bash file there is not response, ie it stays in the same directory. 但是在运行bash文件时没有响应,即,它位于同一目录中。 Why is it so.? 为什么会这样呢? Why doesn't alias work here or should I do something different.? 为什么别名在这里不起作用,还是我应该做些其他的事情?

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). 运行bash文件将无效,因为对当前工作目录的更改将保留在脚本内(因为它是为您提供命令提示符-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_aliases或〜/ .bashrc文件中(最好使用前者,如果前者不存在,则后者可能会更快),然后它应该可以工作。

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 (ie the shell from which you launches the script). 当您启动bash脚本时,它会更改其当前目录然后存在,这对父进程(即从中启动脚本的shell)没有影响。

Instead of running ./script.sh , try source ./script.sh (or . ./script.sh for short). 而不是运行./script.sh ,请尝试使用source ./script.sh (或简称为. ./script.sh )。

Also, defining an alias for cd won't on its own change the directory. 同样,为cd定义alias不会单独更改目录。 I assume you actually invoke the alias somewhere. 我假设您实际上在某个地方调用了别名。

Are you saying you want to write a bash script that will cd to another directory? 您是说要编写一个bash脚本,该脚本将cd到另一个目录吗?

Then why use an alias? 那为什么要使用别名呢? Just use the "cd" command! 只需使用“ cd”命令!

It is because your script is executed in a new shell-process when you call it like ./cd.sh . 这是因为当您像./cd.sh这样调用脚本时,该脚本是在新的shell进程中执行的。 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 您可以像这样调用脚本. cd.sh . cd.sh - this executes the script in the current shell and the cd-command works. . cd.sh这将在当前shell中执行脚本,并且cd-command可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM