Helper functions
Some functions providing nice output formatting and easier user input parsing used by some of my scripts. Get them. Or view them…
#!/bin/bash## Wed Aug 17 11:57:21 CEST 2005 * Miguel de Benito <nonick AT 8027 DOT org>## Helper functions for my scripts## Some colors#BLUE="\033[34;01m"CYAN="\033[36;01m"GREEN="\033[32;01m"RED="\033[31;01m"OFF="\033[0m"## Required tools#[ ! -x /bin/stty ] && error_msg "/bin/stty is required but not found. Bye..."[ ! -x /bin/date ] && error_msg "/bin/date is required but not found. Bye..."## Terminal size#_ROWS=$(/bin/stty size | cut -d" " -f 1)_COLS=$(/bin/stty size | cut -d" " -f 2)##### Outputs info message (no \n)#info_msg(){echo -ne "$1"}##### Outputs status message [OK] [ERR] depending on first parameter#status_msg(){if (( $1 == 0 ))then# Align to the rightmost columnlet pos=_COLS-6echo -e "\033[${pos}G[ ${GREEN}OK${OFF} ]"else# Align to the rightmost columnlet pos=_COLS-9echo -e "\033[${pos}G[ ${RED}ERROR${OFF} ]"fi}##### Outputs colored error messages#error_msg(){echo -e "${RED}$1${OFF}"}##### Reads user input (Y/N)## @arg1 Message# @arg2 Default option (Y/N)## @return 1 if the user answered no, 0 if yes.#ask_msg(){if (( $# != 2))thenerror_msg "ask_msg(): wrong number of arguments"exit 1fiecho -ne "$1 [${BLUE}$2${OFF}] ${BLUE}>${OFF} "read -s -n 1 inp## Uh? This looks ugly. Surely it could be improved.case $2 inn|N)case $inp iny|Y|s|S)echo -e "${CYAN}Yes${OFF}"return 0;;*)echo -e ${BLUE}No${OFF}return 1;;esac;;y|Y|s|S)case $inp inn|N)echo -e "${CYAN}No${OFF}"return 1;;*)echo -e ${BLUE}Yes${OFF}return 0;;esac;;*)error_msg "ask_msg(): incorrect default option '$2'"exit 1;;esac}### Runs a command and shows a status message after completion.# Logs stderr too.## @arg1 Info message# @arg2 Command to run# TODO: better log format, and make filename configurable. Add dates to messages.run_cmd(){local log=/tmp/run_cmd_error.loglocal output=""if (( $# != 2))thenerror_msg "run_cmd(): wrong number of arguments"exit 1fidate=`/bin/date`info_msg "$1"# Run the commandoutput=`eval "$2" 2>&1`status=$?# Check its outputif [ ! -z "$output" ]thenecho -e "run_cmd(): output of command [$2] at [$date]:\n" >> $log# Remember to quote $output to preserve linefeedsecho "$output" >> $logfistatus_msg $status}- Download this code: messages.sh

