6

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.

2
  • print_and_log() - have you considered using tee? Just a suggestion, but it's built to do exactly what that command is doing echo "hello" | tee -a logfile.log would add a line to a file in a similar manner to your function.
    – VLAZ
    Apr 23, 2015 at 19:45
  • I didn't knew tee, but thank you for the hint :)
    – starki
    Apr 24, 2015 at 7:27

1 Answer 1

10

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)"
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .