我的代码一直卡在这个 while 循环中,说明目录不存在,为什么会这样



我有以下代码旨在执行模拟。模拟完成后,它将从输出文件中删除文本,并使用新编辑的输出文件作为新模拟的输入。发生的情况是我陷入了关于 GROPATH 文件存在的 while 循环中。我将以下循环打印到日志文件中:

Directory path exists
GROPATH does not exist
waiting sleep 10800
GROPATH does not exist
waiting sleep 10800
GROPATH does not exist
waiting sleep 10800
GROPATH does not exist
waiting sleep 10800
GROPATH does not exist
waiting sleep 10800
GROPATH does not exist
waiting sleep 10800
GROPATH does not exist
waiting sleep 10800
GROPATH does not exist
waiting sleep 10800
GROPATH does not exist
waiting sleep 10800
GROPATH does not exist
waiting sleep 10800
GROPATH does not exist
waiting sleep 10800
GROPATH does not exist
waiting sleep 10800
GROPATH does not exist
...

它一直这样继续下去。

我很困惑,因为 GROPATH 确实存在,我可以在目录中看到确切的文件。我做错了什么,导致了这个无限循环?我应该改用 if 循环吗?我已经检查了我的文件路径映射,这对我来说似乎是正确的。

#!/bin/bash

#set value of i
i=`k=$(ls md*gro -v1 | tail -n1) ; echo ${k//.gro/} | sed "s/md//"`
# while more than 20 waters ...
while (grep -c SOL  md$i.gro > 20); do
    DIRECTORY=~/scratch/desolvation/iteration_$i
    GROPATH=~/scratch/desolvation/iteration_$i/md$i.gro
    ERRORPATH=~/scratch/desolvation/log_gpu.dat
#does the directory exist?
        if [ -d "$DIRECTORY" ]; then
                echo "Directory path exists"
# does gro file exist?
                while [ ! -d "$GROPATH" ]; do
                        echo "GROPATH does not exist"
                        if grep -q 'error' "$ERRORPATH"; then
                                echo "error in gromacs"; exit
                        else echo "waiting" sleep 10800
                        fi
                done

我希望代码能够识别文件确实存在并继续程序的下一部分(为了保持简洁,我没有包括它(,它编辑 GROPATH 文件,以便它可以用作下一次模拟的输入。

测试[ ! -d "$GROPATH" ]检查该名称的目录,而不是文件。要检查文件,请使用-f而不是-d(或者只使用-e,这将检查该名称的任何内容(。

其他问题:while (grep -c SOL md$i.gro > 20); do没有做你想要的;()创建一个子shell,该子shell运行grep命令,其输出重定向到一个名为"20".请改用while [ "$(grep -c SOL md$i.gro)" -gt 20 ]; do

此外,您echo "waiting" sleep 10800为单个命令,因此它会打印"sleep 10800",而不是将其作为命令执行;只需将其移动到单独的行即可。

你选择i的方式是一团糟;试试这个:

i=$(printf '%sn' md*.gro | sed 's/^md//; s/[.]gro$//' | sort -rg | head -n1)

一般建议:通过 shellcheck.net 运行脚本以发现常见问题。

最新更新