Should I be using a case statement or an if/else

Viewed 59

I am making a script in unix that will read a text file and each record has six fields separated by a pipe. I don't know if I should use a case statement or an if/else statement.

  • If the $JOB has a value of P then NEW_NICE should be set to 3.
  • If the $JOB has a value of S then NEW_NICE should be set to 6.
  • All other values of $JOB should set NEW_NICE to 7.

I kinda wanna use a case statement because it would be simpler, but I also am not sure on how that would look.

1 Answers

I won't tell you which one to use since it's a matter of preference. Either is fine. Let's do some comparison shopping so you can see them side by side.

(It's best to avoid all-uppercase variable names so as not to clash with any of the shell's built-in variables, which are always uppercase. I use job and new_nice below.)

Here's how the case statement would look. Use *) for the default case.

case "$job" in
    P) new_nice=3;;
    S) new_nice=6;;
    *) new_nice=7;;
esac

Here are two versions with if statements. In Bash you can use double brackets to avoid having to quote "$job":

#!/bin/bash

if [[ $job == 'P' ]]; then
    new_nice=3
elif [[ $job == 'S' ]]; then
    new_nice=6
else
    new_nice=7
fi

If you're targeting plain sh then you'll have to use single brackets and quote "$job".

You could also move the else case up top if that looks better. That could be nice if 7 is the default value and 3 and 6 are less common overrides.

#!/bin/sh

new_nice=7
if [ "$job" = 'P' ]; then
    new_nice=3
elif [ "$job" = 'S' ]; then
    new_nice=6
fi
Related