Thursday, March 5, 2009

Print text in style box - bash scripting


The script:


#/bin/bash

_Box () {
str="$@"
len=$((${#str}+4))
for i in $(seq $len); do echo -n '*'; done;
echo; echo "* "$str" *";
for i in $(seq $len); do echo -n '*'; done;
echo
}

_Box "Welcome to AUDIT menu"


Execute the script:

$ ./box.sh
*************************
* Welcome to AUDIT menu *
*************************


Some points on the above script:

a) In the script, _Box is a function for generating style box. Any text sent as its argument will be shown within a stylish text box (as we saw above)

b) $@ : List of all shell arguments (here arguments to the function _Box)

c) len variable will be assigned to length of the string(argument)+4. Read how we can find string length in bash here

d) The for loops will print "len" number of * (read about seq)

e) -n option with echo (-n: do not output the trailing newline)

Related post:
- Generate a chess board pattern in bash scripting

4 comments:

AmirWatad said...

Hey, a great script.
(And a great blog in general).

AmirWatad said...

Hey, a great script.
And a great blog.

Thanks for sharing.

christias said...

or just

_Box () {
echo $@ | sed -e 's/^/../' -e 's/$/../' -e 's/./*/g'
echo $@ | sed -e 's/^/* /' -e 's/$/ */'
echo $@ | sed -e 's/^/../' -e 's/$/../' -e 's/./*/g'
}

Jadu Saikia said...

@Amir, thanks for your compliment.

@christias, its a great idea, thanks.

© Jadu Saikia www.UNIXCL.com