在 shell 脚本中调用 pushd

6 command-line shell

我有一个简单的脚本,我想调用 'pushed' 后跟另一个命令。但是脚本中的“pushd”命令似乎并没有超过脚本。

有什么方法可以让这个在 shell 终端中执行?

#!/bin/sh

pushd $1
time
Run Code Online (Sandbox Code Playgroud)

我真正想要完成的是 invokepushd后跟other-command一个命令。

War*_*ung 8

/bin/sh在这种情况下,shell 脚本通常在单独的 shell 程序实例中执行。您的pushd命令仅影响该子 shell 的工作目录。否则,您从 shell 运行的任何程序都可能与 shell 的工作目录混淆。

要在当前 shell 中执行该脚本,请改为:

$ . my-command somedir
Run Code Online (Sandbox Code Playgroud)

或者,更详细地说:

$ source my-command somedir
Run Code Online (Sandbox Code Playgroud)

为了使您的程序看起来像其他程序一样工作,您可以使用别名:

$ alias mycmd='source my-command'
$ mycmd /bin
$ pwd
/bin
Run Code Online (Sandbox Code Playgroud)

  • shell 脚本是一个很好的方法来做到这一点。这是低效的,但这不是优化值得打扰的情况。在你的 `~/.bash_profile`(或者你的 shell 使用的任何东西,如果不是 Bash)中定义一个 shell 函数也可以。你的选择。 (2认同)