Bash for Windows (Git-Bash) 中 $$ 返回的 PID 错误

问题描述 投票:0回答:1

在任何基于 Unix 的操作系统上的 Bash 中,可以使用

$$
来获取当前 shell 的 PID。然而,它在 Windows 版 Bash(又名 Git-Bash,随 Git 一起安装)中不起作用。

例如,现在在 Windows 10 上,我只打开了一个 Bash 窗口。

echo $$
打印 1294,但任务管理器显示
git-bash.exe
(shell)为 7296,
mintty.exe
(终端仿真器)为 12832。

我想要的是能够通过读取 Bash 脚本写入文本文件中的 PID,从单独的 Batch 脚本(由

cmd.exe
执行)杀死 Bash 脚本(在 Bash 窗口中运行)。我已经掌握了拼图的所有部分,除了从 Bash 编写正确 PID 的方法(批处理脚本显示
ERROR: The process "1294" not found.

我怎样才能实现这个目标?

编辑:经过更多测试,似乎

$!
也表现得不可靠。

编辑2:问题的最小重现:

script.sh

#!/bin/bash

echo $$ >> /tmp/pid.txt
echo "Saved \"$$\" in PID file. Now going to sleep..."
sleep 86400

打印

Saved "2080" in PID file. Now going to sleep...

kill.bat

@for /f "tokens=*" %%a in (%TEMP%\pid.txt) do (
    taskkill /pid %%a
)
@del %TEMP%\pid.txt

打印

ERROR: The process "2080" not found.

windows bash git-bash pid
1个回答
0
投票

而不是:

echo $$ >> /tmp/pid.txt

尝试以下方式获取 Windows PID:

ps -p $$ | awk 'NR ==2{print $4}' >> /tmp/pid.txt
© www.soinside.com 2019 - 2024. All rights reserved.