Unable to redirect bash output to variable file name Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Unable to redirect bash output to variable file name without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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 test@$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 "test@$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 "test@$server" 'uname -n' >"/tempout/uname_$var.txt"
done <servers
We are here to answer your question about Unable to redirect bash output to variable file name - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji