Bash – Redirection to File Does Not Work Properly

bashio-redirectionlogsping

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.

Best Answer

The "Network is not reachable" message is printed to stderr, not stdout, so it isn't captured by your substitution ($(ping ...)). You need to redirect stderr to stdout when running ping, not when you log:

    print_and_log "$(ping -c10 "$i" 2>&1)"
Related Question