Unable to redirect bash output to variable file name

I am trying to redirect the bash output to a variable file name. Here is my script looks like

#!/bin/bash
for i in `cat servers`
do
if [ "$i" = "198.162.1.3" ];
then
var="apple"
fi
ssh [email protected]$i "uname -n"
done > /tempout/uname_${var}.txt

I am getting the filename as /tempout/uname_.txt

Expected filename should be uname_apple.txt

Answer

The var variable in your code is used before the loop starts to create the output file.

If you want to output the result of the ssh command to a file whose name you construct from $var, then do this:

#!/bin/bash

while read -r server; do
    if [ "$server" = "198.162.1.3" ]; then
        var='apple'
    else
        var='unknown'
    fi

    ssh -n "[email protected]$server" 'uname -n' >"/tempout/uname_$var.txt"
done <servers

Here, I’ve also changed the loop so that it reads the input file line by line (ignoring leading and trailing whitespace on each line), and I’ve made var get the value unknown if the if statement does not take the “true” branch.

Also, you need -n for ssh. Otherwise, ssh would consume all the available input (here redirected from the servers file).

Another change that could be made is to use case ... esac rather than an if statement, especially if the number of IP addresses that you test for is more than a couple:

#!/bin/bash

while read -r server; do
    case $server in
        198.162.1.3) var=apple ;;
        198.162.1.5) var=cottage ;;
        198.162.1.7) var=bumblebee ;;
        *) var=unknown
    esac

    ssh -n "[email protected]$server" 'uname -n' >"/tempout/uname_$var.txt"
done <servers

Leave a Reply

Your email address will not be published. Required fields are marked *