Wednesday, January 10, 2007

BASH Hacks: Prompting For Data With a Text Editor and a Prompt

Often times your BASH script will require additional data to be passed via parameter to the script, if the user doesn't pass data to the script, the traditional way of handling this is to check for the paramater and then if it doesn't exist or doesn't match the proper format to quit with an usage message:


#!/bin/bash
if [ -z $1 ]
then

echo "Usage: {x|y|z}"
exit 0

fi


Sometimes this is appropriate, whereas other times, the user might just not know how to use the script, or might have forgotten. In my work I end up having to write a lot of scripts to help my developers do what they need to do on a daily basis, alot of times these scripts will only be called once a week, and require data input that they might just forget about. So . . . to help them with this i use a text editor and a prompt at the beginning of a file to get the data from them after the script has started. Here is a template of the code I use:


#!/bin/bash

#######################################
# textedit.sh
#
# A template for prompted text editor
# data entry from a bash script
#######################################

##########VARIABLE DEFINITION############

# This needs to start with a #, the reason for this will become clear later
PROMPT="################INSERT DATA HERE#################"

# Set DATA equal to the parameter
DATA=$1

# command for your favorite text editor
TEXTEDITOR="vim"

# name of text file
TEXTFILE=".bash.script.text.txt"
######################################

while [ -z "$DATA" ]
do

# add PROMPT to beginning of file
echo "$PROMPT" > ~./$TEXTFILE

# add a trailing line
echo 1>> ~/$TEXTFILE

#open file in favorite text editor
$TEXTEDITOR ~/$TEXTFILE

#check to see if they added anything
DATA=$(cat ~/$TEXTFILE | grep ^[^#])

#delete the file
rm ~/$TEXTFILE

done

## actions here

exit 0



So basically what this does is it checks to see if $1 was passed as a parameter, if it's not it puts the prompt and an extra empty line into the text file that you specified and opens up the text editor with the prompted file in it for editing. After this, it checks to see if any lines without the opening # are in the file, if there are then the loop is satisfied, if not it keeps at it untill the user puts something in the file.

Enjoy!

No comments: