我对bash相当陌生,所以如果我的代码看起来不太好或者不正确,请放心。
我现在试着做一个脚本,它将平一个主机名,如果那个主机名没有响应,它将获取主机名的IP,并尝试它。似乎毫无意义,但我有自己的理由。
我遇到的问题是,我的脚本没有在脚本的末尾识别“已完成”。
#!/bin/bash
#while read hostname; do
for hostname in $(cat host.txt); do
ping -c1 $hostname 1>/dev/null 2>/dev/null
SUCCESS=$?
if [ $SUCCESS -eq 0 ]
then
echo "$hostname has replied"
else#[ $SUCCESS -ne 0 ]
echo "Hostname didn't reply, trying IP"
ip=`cat /etc/hosts | grep $hostname | awk '{print $1}' `
ping -c1 $ip 1>/dev/null 2>/dev/null
SUCCESS=$?
if [ $SUCCESS -eq 0 ]
then
echo "$ip has replied"
echo "------------------------------"
else
echo "$ip didn't reply"
echo "------------------------------"
fi
done发布于 2022-06-01 01:46:46
我对代码进行了重新格式化,以更标准和更通用的方式缩进代码。我还添加了一些可能有助于人们学习基础知识的评论,比如4年前的@Root_。你可以检查一下:
#!/bin/bash
# I just used an editor that can do formatting of code.
# I asked it to reindent all lines within my settings.
# There are several programs to do this. I used vim.
for hostname in $(cat host.txt); do
ping -c1 $hostname 1>/dev/null 2>/dev/null
SUCCESS=$?
# ping ended successfully?
if [ $SUCCESS -eq 0 ] then
echo "$hostname has replied"
else
echo "Hostname didn't reply, trying IP"
ip=`cat /etc/hosts | grep $hostname | awk '{print $1}' `
ping -c1 $ip 1>/dev/null 2>/dev/null
SUCCESS=$?
# ping ended successfully?
if [ $SUCCESS -eq 0 ] then
echo "$ip has replied"
echo "------------------------------"
else
echo "$ip didn't reply"
echo "------------------------------"
fi
fi
# You missed this last "fi". With good indentation,
# we see it easily. And with an editor that is done
# for developers, it may even point us a place to
# look for errors. In this case, the "done" was
# written in red, which helped me asking 2 questions:
# 1. Is this done in the right place? Where is its
# corresponding "do"? (it is on on line 7 now)
# 2. So, if the done is correct, what else is wrong?
# Then, for the indentation I did, it was easy to see
# the 'if' on line 13 did not have a 'fi'.
donehttps://stackoverflow.com/questions/46817903
复制相似问题