Happy Birthday Bash Script

29th October 2012 - 1 minute read time

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.

  1. #!/bin/bash
  3. output=''
  4. for i in {1..4}
  5. do
  6. output=$output"Happy birthday "
  8. if [ $i -eq 3 ]
  9. then
  10. output=$output"dear $1\n"
  11. else
  12. output=$output"to you\n"
  13. fi
  14. done
  16. 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


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"

Miriam English (Sun, 11/26/2017 - 19:49)

Add new comment

The content of this field is kept private and will not be shown publicly.