$ tpgid=$(ps --no-headers -o tpgid -p 1)
$ echo $tpgid
-1
$ if [[ $tpgid == "-1" ]]; then
> echo "yes"
> else
> echo "no"
> fi
no
Run Code Online (Sandbox Code Playgroud)
为什么条件不成立?谢谢。
$ printf "%s" "$tpgid" > /tmp/test/fff
$ hd /tmp/test/fff
00000000 20 20 20 2d 31 | -1|
00000005
Run Code Online (Sandbox Code Playgroud)
尽管[[ ... ]]
比[ ... ]
or更“聪明” test ...
,但显式使用数值比较运算符仍然是一个更好的主意:
if [[ "$tpgid" -eq -1 ]]; then ...
Run Code Online (Sandbox Code Playgroud)
此外,您的十六进制转储:
$ hd /tmp/test/fff
00000000 20 20 20 2d 31 | -1|
Run Code Online (Sandbox Code Playgroud)
显示$tpgid
扩展为" -1"
, not "-1"
; -eq
知道如何处理这个问题,同时==
正确地进行字符串比较:
$ if [[ " -1" == -1 ]]; then echo truthy; else echo falsy; fi
falsy
$ if [[ " -1" -eq -1 ]]; then echo truthy; else echo falsy; fi
truthy
Run Code Online (Sandbox Code Playgroud)
简而言之,字符串匹配条件没有返回真,因为字符串实际上不匹配。