File handling using Shell Scripts
- to prepend a line to a file
- to develop a temporary file name generator
- to compare two files
Requirements:
Suse Linux, BASH Scripting
Program
(a) Prepending a line to a file
#!/bin/bash
# prepend.sh: Add text at beginning of file.
E_NOSUCHFILE=65
read -p "File: " file # -p arg to 'read' displays prompt.
if [ ! -e "$file" ]
then # Bail out if no such file.
echo "File $file not found."
exit $E_NOSUCHFILE
fi
read -p "Title: " title
cat - $file <<<$title > $file.new
echo "Modified file is $file.new"
exit 0
(b) to develop a temporary file name generator
#!/bin/bash
# tempfile-name.sh: temp filename generator
BASE_STR=`mcookie` # 32-character magic cookie.
POS=11 # Arbitrary position in magic cookie string.
LEN=5 # Get $LEN consecutive characters.
prefix=temp # This is, after all, a "temp" file.
# For more "uniqueness," generate the filename prefix
#+ using the same method as the suffix, below.
suffix=${BASE_STR:POS:LEN}
# Extract a 5-character string, starting at position 11.
temp_filename=$prefix.$suffix
# Construct the filename.
echo "Temp filename = "$temp_filename""
# sh tempfile-name.sh
# Temp filename = temp.e19ea
exit 0
(c) Comparing two files
#!/bin/bash
ARGS=2 # Two args to script expected.
E_BADARGS=65
E_UNREADABLE=66
if [ $# -ne "$ARGS" ]
then
echo "Usage: `basename $0` file1 file2"
exit $E_BADARGS
fi
if [[ ! -r "$1" || ! -r "$2" ]]
then
echo "Both files to be compared must exist and be readable."
exit $E_UNREADABLE
fi
cmp $1 $2 &> /dev/null # /dev/null buries the output of the "cmp" command.
if [ $? -eq 0 ] # Test exit status of "cmp" command.
then
echo "File \"$1\" is identical to file \"$2\"."
else
echo "File \"$1\" differs from file \"$2\"."
fi
exit 0
Observation:
Open the VI editor
$: vi <filename>
Compile using bash
$: sh <filename>
Comments
Post a Comment