I have here a bash script:
#!/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
My aim is to print the same output into a file and into console. But when I disconnect my operation system from the network, then in the console, I see (for example for the first IP address):
----- Begin Pinging for XXX.XXX.XXX.XXX ---
command: ping -c10 XXX.XXX.XXX.XXX
connect: Network is not reachable
----- Pinging for XXX.XXX.XXX.XXX end -----
But in the file, I do no see any message, that the Network is not reachable. Why? How can I change my bash script, that I also can see this message in my logging file.
print_and_log()
- have you considered using tee? Just a suggestion, but it's built to do exactly what that command is doingecho "hello" | tee -a logfile.log
would add a line to a file in a similar manner to your function.tee
, but thank you for the hint :)