Not getting the right output for Element.sh – Build A Periodic Table Database Project

:wave:

I am stuck on the task

If you run ./element.sh 1 , ./element.sh H , or ./element.sh Hydrogen , it should output The element with atomic number 1 is Hydrogen (H). It's a nonmetal, with a mass of 1.008 amu. Hydrogen has a melting point of -259.1 celsius and a boiling point of -252.9 celsius."

Here is the current code in my bash script

# return result
 echo "$ELEMENT_RESULT"| while read AUTOMIC_NUM BAR SYMBOL BAR NAME BAR ATOMIC_MASS BAR MPC BAR BPC BAR TYPE
   do
      echo "The element with the atomic number $AUTOMIC_NUM is $NAME($SYMBOL). It's a $TYPE, with a mass of $ATOMIC_MASS amu. $NAME has a melting poing of $MPC celcius and a boiling poing of $BPC celcius."
   done

When I run the script I get:

The element with the atomic number 1|H|Hydrogen|1.008|-259.1|-252.9|nonmetal is (). It’s a , with a mass of amu. has a melting poing of celcius and a boiling poing of celcius.

If I echo just the $ELEMENT_RESULT I get this output

1|H|Hydrogen|1.008|-259.1|-252.9|nonmetal

As you can see, the while loop is not picking out the variables. :thinking: I’m not sure why.

What am I missing? Any help would be greatly appreciated.

-Richard

Try logging your AUTOMIC_NUM variable. I’m guessing it contains 1|H|Hydrogen|1.008|-259.1|-252.9|nonmetal. (Edit: looks like you did that, I must have glossed over it.) This is cause there’s no spaces in that text. Spaces are the default separator - since there isn’t any, it just sets everything to the first variable. Pretty sure there was a few steps in the lessons about the IFS. I would try setting it to |. So it would be something like this:

 echo "$ELEMENT_RESULT"| while IFS = "|" read AUTOMIC_NUM SYMBOL NAME ATOMIC_MASS MPC BPC TYPE
   do
      echo "The element with the atomic number $AUTOMIC_NUM is $NAME($SYMBOL). It's a $TYPE, with a mass of $ATOMIC_MASS amu. $NAME has a melting poing of $MPC celcius and a boiling poing of $BPC celcius."
   done

For some more info - IFS stands for internal field separator, setting it to the pipe (|) would then (hopefully) separate your text between each of the pipes instead of the spaces that aren’t there.

1 Like

Got it! :clap:

IFS worked! Below is the solution that worked for me…hopefully it helps someone else in the future. Thanks @moT01

Solution

echo “$ELEMENT_RESULT” | while IFS="|" read AUTOMIC_NUM SYMBOL NAME ATOMIC_MASS MPC BPC TYPE
do
echo “The element with atomic number $AUTOMIC_NUM is $NAME ($SYMBOL). It’s a $TYPE, with a mass of $ATOMIC_MASS amu. $NAME has a melting point of $MPC celsius and a boiling point of $BPC celsius.”
done

1 Like