Linux Bash:循环需要继续从文件忽略失败的其他条目;失败消息
我需要一些帮助来修改我的脚本。它是为在一台设备上完成同样的工作而编写的。我试图以某种方式修改脚本,以便它在已知的\u hosts文件中检查已知的ssh密钥,以获得IP地址列表。如果一台设备出现故障,则应显示相应的错误并继续使用另一台设备。我正在从一个文件中植入IP地址。到目前为止,我所拥有的代码如下Linux Bash:循环需要继续从文件忽略失败的其他条目;失败消息,linux,bash,shell,Linux,Bash,Shell,我需要一些帮助来修改我的脚本。它是为在一台设备上完成同样的工作而编写的。我试图以某种方式修改脚本,以便它在已知的\u hosts文件中检查已知的ssh密钥,以获得IP地址列表。如果一台设备出现故障,则应显示相应的错误并继续使用另一台设备。我正在从一个文件中植入IP地址。到目前为止,我所拥有的代码如下 #!/bin/bash #filename=test-file.txt #while IFS= read -r ip in $filename set +e for ip in $(cat test
#!/bin/bash
#filename=test-file.txt
#while IFS= read -r ip in $filename
set +e
for ip in $(cat test-file.txt)
do
echo $ip
if [ -z "$ip" ]
then
echo " ERR - IP Adress not specified" #|| true
#exit 1
fi
# Check if input is a valid IP address
checkregex="[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
if [[ $ip =~ $checkregex ]]
then
echo "OK - Input is a valid IP address" #> /dev/null 2&>1
else
echo "ERROR - Invalid input" #|| true
#exit 1
fi
# Get linenumber and remove the key from known_hosts file
linenumber="$(egrep -m1 -n "$ip " /home/username/.ssh/known_hosts | cut -d':' -f1)"
i=1
while [ $i -gt 0 ]
do
if [ -z "$linenumber" ]
then
echo "WARN - No stored SSH key found for this device" #> /dev/null 2&>1
i=0
#exit 0
fi
echo "OK - SSH key found at line number ${linenumber} - Going to remove it" #> /dev/null 2&>1
sed -i "${linenumber} d" /home/username/.ssh/known_hosts
echo "OK - Key removed - Retry config capture on the device"
linenumber="$(egrep -m1 -n "$ip " /home/username/.ssh/known_hosts | cut -d':' -f1)"
if [ -z "$linenumber" ]
then
echo "OK - No more stored SSH key found for this device" #> /dev/null 2&>1
i=0
fi
done
#exit 0
done #< $filename
xx.xx.xx.xx (IP Address)
OK - Input is a valid IP address
WARN - No stored SSH key found for this device
OK - SSH key found at line number - Going to remove it
OK - Key removed - Retry config capture on the device
OK - No more stored SSH key found for this device
如果我注释掉出口1或出口0,那么它将继续进行。如果没有,它将为列表中的第一个IP执行并存在
我试图用多种方式修改脚本,但没有多大帮助(您可以看到我尝试过的许多注释条目)
提前感谢你的帮助
Soumyadipta Ganguly你能提供一个输入文件的例子吗?请通过
标记/bash/info
的部分进行操作。(并查看同一链接中的“如何将糟糕的脚本转化为好问题”部分)。祝你好运。(你可以看到我试过的许多评论条目)。您肯定要放弃$(cat…循环中ip的,并在读取文件名时切换到;做完成<$inputile
循环形式。同样echo“WARN…”#>/dev/null 2>&1
和其他类似的词没有意义,即使没有注释字符。为什么/dev/null
会出现任何警告或错误消息?否则会有太多的事情发生,所以请参见上面的内容,并对您的问题做一个小得多的版本。你很可能会自己解决的!Goodluck输入类似于以下内容。xx.xx.xx.xx yy.yy.yy zz.zz.zz.zzexit
将结束整个脚本,break
将结束整个循环,continue
将结束当前迭代。你的问题是什么?你能提供一个输入文件的例子吗?请通过tags/bash/info
的一节来学习。(并查看同一链接中的“如何将糟糕的脚本转化为好问题”部分)。祝你好运。(你可以看到我试过的许多评论条目)。您肯定要放弃$(cat…
循环中ip的,并在读取文件名时切换到;做完成<$inputile
循环形式。同样echo“WARN…”#>/dev/null 2>&1
和其他类似的词没有意义,即使没有注释字符。为什么/dev/null
会出现任何警告或错误消息?否则会有太多的事情发生,所以请参见上面的内容,并对您的问题做一个小得多的版本。你很可能会自己解决的!Goodluck输入类似于以下内容。xx.xx.xx.xx yy.yy.yy zz.zz.zz.zzexit
将结束整个脚本,break
将结束整个循环,continue
将结束当前迭代。你的问题是什么?