为什么我的 shell 脚本在没有 .sh 扩展名的情况下挂起?

Chr*_*way 6 bash scripts

我创建了一个/usr/local/bin/suspend包含以下内容的 shell 脚本:

#! /bin/sh

# Take an optional delay parameter
if [ "$#" -gt "0" ]; then
  sleep "$1"
fi

# Put the system to sleep
dbus-send --system --print-reply --dest="org.freedesktop.Hal" \
    /org/freedesktop/Hal/devices/computer \
    org.freedesktop.Hal.Device.SystemPowerManagement.Suspend \
    int32:0
Run Code Online (Sandbox Code Playgroud)

如果我chmod +x通过直接调用(例如,仅键入suspend/usr/local/bin/suspend在命令行上)来运行脚本,则不会发生任何事情并且 shell 会挂起——它甚至不响应 Ctrl-C;我必须切换到一个新的 shell 并终止该bash进程(没有明显的子进程)。

如果我通过以下任何一种方式调用该脚本,则该脚本可以正常工作:

  • 使用sh /usr/local/bin/suspend.
  • 使用. /usr/local/bin/suspend.
  • 将其重命名为suspend.sh并调用/usr/local/bin/suspend.sh(或只是suspend.sh,因为它在 中PATH)。

最后一个选项很好,但我仍然想知道:不使用.sh扩展到底有什么问题?

Chi*_*aca 10

suspend 是一个内置的 bash,

suspend: suspend [-f]
Suspend shell execution.

Suspend the execution of this shell until it receives a SIGCONT signal.
Unless forced, login shells cannot be suspended.

Options:
  -f    force the suspend, even if the shell is a login shell

Exit Status:
Returns success unless job control is not enabled or an error occurs.
Run Code Online (Sandbox Code Playgroud)

并且由于内置函数优先,只需键入suspend就会完全按照您的描述进行操作:shell 会阻塞,直到您将其杀死(如果kill -CONT是,则它会恢复)。

通过使用路径调用它,您会看到相同的行为,这要么是实验性错误,要么是 shell 中的错误。在后者之前,我会怀疑前者。