【问题标题】:sh shell script on windows causes error: /dev/tty: No such device or addressWindows 上的 sh shell 脚本导致错误:/dev/tty: No such device or address
【发布时间】:2019-06-29 02:28:18
【问题描述】:

在 git commit-msg 中的 Windows 上,我想运行以下脚本:

MSG="$1"
if ! grep -s -qE "#[0-9]" "$MSG";then
    exec < /dev/tty
    cat "$MSG"
    echo "Your commit message does not contain a reference to a work item. Continue? [y/n]"
    read -s -n 1 sure
    if [[ $sure == "y" ]]; then
        exit 0
    else
        echo "Aborting commit..."
        exit 1
    fi
fi

当我使用 Git 扩展时它运行良好。

但是,当我想直接从 Visual Studio(团队资源管理器或 Git 更改)提交时,会出现以下错误消息:

Your git-hook, '.git/hooks/commit-msg' (line 23) is not supported, likely because it expects interactive console support./r/nSee your administrator for additional assistance.

我的问题: 有没有可能检查 exec/tty 是否可以执行?否则我只会打印一条相应的消息。

提前致谢。

【问题讨论】:

    标签: git sh githooks


    【解决方案1】:

    您可以使用if [ -t 1 ]if [ -t 2 ] 来测试您是在管道中还是在终端中。

    if [ -t 1 ]; then    # or if [ -t 2 ]
       # do interactive stuff
    else
       # non-interactive variant
    fi
    

    参考:How to detect if my shell script is running through a pipe?

    编辑:OP 报告我原来的答案中的 [ -t 1 ] 不起作用,但 [ -t 2 ] 起作用。第一个测试 stdout 到 tty,第二个测试 stderr 到 tty。在这种情况下,我猜测 Git Extensions 和 Visual Studio 都会捕获脚本的标准输出,但 Git Extensions 会将标准错误发送到 tty,而 Visual Studio 也会捕获它。

    【讨论】:

    • 感谢您的回答。我之前已经尝试过,但没有成功。根据该测试,它始终处于#non-interactive 变体中。但至少有了 git 扩展,我才有了交互的可能
    • 我想问题是当从 Git 扩展启动时,输出可能仍在管道中。你也试过[ -t 0 ][ -t 2 ]吗?我想如果[ -t 1 ] 没有,它们也不会工作,但你永远不知道。测试来自exec 的返回码怎么样?这应该会失败,在这种情况下,if exec &lt; /dev/tty; then interactive variant; else non-interactive variant; fi 之类的东西可能会起作用。
    猜你喜欢
    • 2014-03-14
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多