bashshellif-statementrepeatcode-cleanup

How to make below bash script clean and less repetitive?


I'm making birthday tracker for only a few people and was wondering how to combine all if statements into one since date and name are the only different things in every if statement, rest is same format.

date=`date +%b-%d`
echo $date

if [ $date  == "Sep-09" ]; then
    echo "Happy Birthday abc!"
fi

if [ $date  == "Oct-11" ]; then
    echo "Happy Birthday xyz!"
fi
.
.
.

I think I can use positional arguments ($1 for date, $2 for name..) but can't figure out how to use it for multiple dates and names. Or if there's any better way, that would be good to know as well.


Solution

  • Using case:

    ...
    case "$date" in
        "Sep-09") name=abc;;
        "Oct-11") name=xyz;;
           ...
               *) exit;; # if no condition met
    esac
    
    echo "Happy Birthday $name!"