Happy Birthday Bash Script

Following on from the PHP script to print happy birthday I wanted do the same in a bash script. I don't really use bash for much more than stringing together commands so I had to figure out how to do loops and if statements using the simple bash syntax. I also wanted to pass the name of the person as an argument, rather than hard code it into the script. This is what I came up with.

#!/bin/bash

output=''
for i in {1..4}
do
  output=$output"Happy birthday "

  if [ $i -eq 3 ]
  then
    output=$output"dear $1\n"
  else
    output=$output"to you\n"
  fi
done
 
echo -e $output

Save the file as happy.sh or similar and run it in the following way (Name is the argument that we pass to the script).

$ ./happy.sh Name

Comments

Nice. Add some ANSI sequences to make it more festive.\e[31m sets text to red\e[43m sets background to yellow\e[1m sets bold text (on some older terminals it might set bright colors)\e[0m resets all to original settings They can be strung together with semicolons as \e[31;43;1mIt's even better if you add spaces to the beginning of "Happy birthday " and after "to you \n" (before the newline) to pad each line to the name length. Find the length of the passed name with "${#1}" which returns the number of characters in the passed string, then pad with spaces with printf "%${n}s"
#! /bin/sh

n=${#1}
pad=$(printf "%${n}s")
str=''
for i in {1..4}
do
  str=$str"  \e[31;43;1m  Happy birthday "
  if [ $i -eq 3 ]
  then
    str=$str"Dear $1  \e[0m\n"
  else
    str=$str"to you ${pad}\e[0m\n"
  fi
done
echo -e "\n$str"
Permalink

Good effort Job. Excellent work! :)

Name
Philip Norton
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
4 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.