I have a file called namelist with names like this:georgecindychesterI'm using nl namelist to produce: 1 george2 cindy3 chesterI want to use that name list in a script that contains something like this:while [ true ]; doread -p Who are you?  NAMEIDNAME=$(sed ''$NAMEID'q;d' namelist)if $NAME;     then        echo Hello.        return    else        echo Sorry, that's not a valid name.fidonewherein $NAMEID has valid values of 1, 2, and 3.  I'd like $NAME to be false if $NAMEID is anything other than 1, 2, or 3, such as 97 or fasdhj.  sed always gives me an exit value of 0.  awk 'NR==$NAMEID {print; err = 1}' namelist does the same.Right now I'm using OS X 10.11, but I'm planning to use Ubuntu 16.04 when I finish the script.
How can I print the nth line of a file, and detect whether the process failed?
shell script;text processing;sed;awk
Change your NAME variable definition so that it returns the person's name, and we can test on that.  The first thought might be something likeNAME=$(sed -n ${NAMEID}p namelist)But this has potential problems with NAMEID holding bad data (what if someone enters hello or -10..).So instead we'll use awk instead:NAME=$(awk -vNAMEID=$NAMEID 'NR==NAMEID { print ; exit }' namelist)Now it'll be empty if the value is out of range, or hold the user's name.  $ cat namelistgeorgecindychester$ cat tstscriptgetname(){  while [ true ]; do    read -p Who are you?  NAMEID    NAME=$(awk -vNAMEID=$NAMEID 'NR==NAMEID { print ; exit }' namelist)    if [ -n $NAME ]    then      echo Hello $NAME.      return    else      echo Sorry, that's not a valid name.    fi  done}getname$ bash tstscript Who are you? 4Sorry, that's not a valid name.Who are you? helloSorry, that's not a valid name.Who are you? -45Sorry, that's not a valid name.Who are you? 2Hello cindy.