如何使用脚本更改目录


Answers:


14

您需要source您的脚本。如果不是,它将在单独的子shell中运行,请更改子shell的工作目录,但不要更改您在其中运行的shell的工作目录。

来源:

. myfile.sh

要么

source myfile.sh

你可以在这里阅读更多


我只是要添加一个.... UAdadapter,如果您正在运行像sh myfile.sh或./myfile.sh这样的shelll脚本,它将按danjil所述运行。danjil的任何一种选项都可以为您工作。
itnet7 2011年

3

使用exec bash

bash脚本在其当前环境或其子级环境上运行,但绝不在其父级环境上运行。

但是,经常会问这个问题,因为一个人想在另一个目录中执行bash脚本后,留在某个目录中的bash提示符下。

如果是这种情况,只需在脚本末尾执行一个子bash实例:

#!/bin/bash
cd /home/user/somedir
exec bash
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.