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

for i in `cat servers`
if [ "$i" = "" ];
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


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:


while read -r server; do
    if [ "$server" = "" ]; then

    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:


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

    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 *