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

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


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 "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:


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

    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