Optimize the nested IF

Hi,
I have to assign a value for a varaiable based on a Input. I have written the below code:

if [ "$procnam" == "admission" ]
 then
  nf=65
elif [ "$procnam" == "reporting" ]
 then
  nf=46
elif [ "$procnam" == "transfer" ]
 then
  nf=164
elif [ "$procnam" == "diagnosis" ]
 then
  nf=545
elif [ "$procnam" == "emergeny" ]
 then
  nf=56
elif [ "$procnam" == "inpatient" ]
 then
  nf=37
else
exit 0
fi 

Can someone give me an idea of how to optimize it/make this short?
Also, what should be done to do a incase-sensivite comparison?

Like,

if [ "$procnam" == "Admission" ]
 then
  nf=65
elif [ "$procnam" == "REPORTING" ]
 then
  nf=46
...
fi

:rolleyes:

How about:

case $procnam in
  admission ) nf=65  ;;
  reporting ) nf=46  ;;
  transfer  ) nf=164 ;;
  diagnosis ) nf=545 ;;
  emergency ) nf=56  ;;
  inpatient ) nf=37  ;;
esac

To make it case insensitive you could convert procnam to lowercase first:

procnam=$(echo "$procnam" | tr [:upper:] [:lower:])
1 Like

Thanks It works. Also, how to mark a thread as Solved / Closed in this forum?

Why close it? You may get other useful or more optimum answers.

For example, in bash4 you can use parameter expansion to make it case-insensitive:

case ${procnam,,} in
  admission ) nf=65  ;;
  reporting ) nf=46  ;;
  transfer  ) nf=164 ;;
  diagnosis ) nf=545 ;;
  emergency ) nf=56  ;;
  inpatient ) nf=37  ;;
esac
2 Likes