Loop overwrite first input

 function one {
      echo "Who is here?"
      read name
 
      echo "Who old are you $name?"
      read age
 
      if [ "$name" == "Sam" ]; then
           Sam="$age"
           else
           Sam="26"
       fi
 
       if [ "$name" == "Jack" ]; then
             Jack="$age"
             else
             Jack="49"
             fi
 
       echo "is there any one else ?"
        read ans
 
        if [ "$ans" == "yes" ]; then
               one;
        else
               print;
         fi
    }
 
 function print {
              echo "Sam($Sam)"
              echo "Jack($Jack)"
     }
 echo "Hi"
 one;
  
 

The output is

 Hi
 Who is here?
 Sam
 Who old are you Sam?
 43
 is there any one else ?
 yes
 Who is here?
 Jack
 Who old are you Jack?
 10
 is there any one else ?
 no
 Sam(26)
 Jack(10)
 

I don't want to overwrite the first input age. I want the output to have the new age for both names. so for the above input , I want the output to be:-

Sam(43)
Jack(10)

#!/bin/sh

function one ()
{
      echo "Who is here"
      read name
      echo "Who old are you $name"
      read age

      [[ "$name" == "Sam" ]] && Sam=$age
      [[ "$name" == "Jack" ]] &&  Jack=$age

      echo "is there any one else ?"
      read ans

      [[ "$ans" == "yes" ]] && one || print
    }

function print () {
  [[ -z "${Sam}" ]] && echo "Sam(26)" || echo "Sam($Sam)"
  [[ -z "${Jack}" ]] && echo "Jack(49)" || echo "Jack($Jack)"
}

echo "Hi"
one;
1 Like

That's because the second time you (recursively) call function one, the else branch of if [ "$name" == "Sam" ]; will be taken.

BTW, you have a 16 bit char (0x 3000000, UTF8: 0xE3 0x80 0x80) in two seemingly empty lines that cause "command not found" errors in my bash shell.

2 Likes

excellent ,thank you . that's work with me

RudiC,
yeah I do see the problem but I did not know how to fix , however , the way pravin27 provided helped. thank you