在xfce4 4-终端中,我执行:
if [[ $(pgrep -x xfce4-terminal) ]]; then echo "there are files" > test.txt; else echo "no files found" > test.txt; fi它用there are files编写test.txt。如果我在一个shell脚本中执行相同的操作,即当said xfce4-终端仍处于打开状态时,它会在test.txt中写到:D4:
if [[ $(pgrep -x xfce4-terminal) ]]; then echo "there are files" > test.txt; else echo "no files found" > test.txt; fi为什么是这种情况,我要做什么才能修复这个问题(使shell脚本像shell一样)?
<>检查 $(pgrep -x xfce4-terminal)
来自航站楼:
echo $(pgrep -x xfce4-terminal) > toast.txt
# 8257来自shell脚本:
echo $(pgrep -x xfce4-terminal) > toast.txt
# 8257发布于 2022-04-27 22:46:21
[[ ... ]]扩展测试结构首先出现在ksh中,随后被包括bash和zsh在内的其他shell复制。
如果您尝试在一个简单的POSIX /bin/sh中使用它(例如,可能是因为省略了shebang (参见哪个壳解释器运行脚本而不使用壳?) ),它将导致语法错误--这将导致if条件失败,而不管测试的真实性如何。例如:
$ bash -c 'if [[ 1 -eq 1 ]]; then echo "equal"; else echo "not equal"; fi'
equal 但
$ sh -c 'if [[ 1 -eq 1 ]]; then echo "equal"; else echo "not equal"; fi'
sh: 1: [[: not found
not equal<#>但是,[[ $(pgrep -x xfce4-terminal) ]]并不是测试是否存在一个名为xfce4-terminal的正在运行的进程的最佳实践,即使shell支持它。不使用命令替换$(...)来捕获pgrep命令的标准输出,并测试它是否为非空字符串,您可以直接使用pgrep的退出状态。来自man pgrep:
EXIT STATUS
0 One or more processes matched the criteria. For pkill the
process must also have been successfully signalled.
1 No processes matched or none of them could be signalled.
2 Syntax error in the command line.
3 Fatal error: out of memory etc.所以
if pgrep -x xfce4-terminal >/dev/null; then
echo "there are files" > test.txt
else
echo "no files found" > test.txt
fi它将在任何类似Bourne的shell中工作(sh,ksh,bash,zsh)。
发布于 2022-04-27 22:02:32
在终端版本中,有[[ ]],它计算其内容,如果内容有效,返回退出状态为0,否则返回1。如果只传递一个字符串,则如果字符串长度> 0,则返回0,否则返回1。由于您的命令找到了一些内容,所以它返回长度> 0的字符串,[[ ]]返回状态为0或“true”。
shell脚本中的if使用if语句的返回值来确定是执行then还是else。如果返回值为0,则执行then,否则跳到else。
但是,如果您检查man pgrep,它将返回“一个或多个符合条件的进程”的退出代码1。因此,if将其视为使用非零错误代码退出,并跳到else。
为了解决这个问题,只需将[[ ]]放在shell脚本版本中即可。
https://askubuntu.com/questions/1405106
复制相似问题