我这里有一个 bash 脚本:
#!/bin/bash
TARGET_FILE=ping_result.txt
# declare the target ip addresses
declare -a ips=("XXX.XXX.XXX.XXX" "YYY.YYY.YYY.YYY")
function print_and_log() {
echo "$1"
echo "$1" >> $TARGET_FILE 2>&1
}
# loop through all ip addresses
for i in "${ips[@]}"
do
print_and_log "----- Begin Pinging for $i --- "
print_and_log "command: ping -c10 $i"
print_and_log $(ping -c10 $i)
print_and_log "----- Pinging for $i end ----- "
done
Run Code Online (Sandbox Code Playgroud)
我的目标是将相同的输出打印到文件和控制台中。但是当我断开操作系统与网络的连接时,在控制台中,我看到(例如第一个 IP 地址):
----- Begin Pinging for XXX.XXX.XXX.XXX ---
command: ping -c10 XXX.XXX.XXX.XXX
connect: Network is not …Run Code Online (Sandbox Code Playgroud)