Happy Birthday Bash Script

Monday, October 29, 2012 - 11:58

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/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
Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

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;1m It'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"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#! /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"

Add new comment