Dante
Dante

Reputation: 119

Assign exit status and arguments with shell script (unix)

For all the files (in the current directory) that contain the WORD that is the 1st command line argument, I have to insert the second command line argument on a new line at the head of the file.Then I have to Print usage and exit with status 4 if not given two args. Exit status 1 is there were there are no such files. Exit status 2 if any of the files could not be altered. Exit status 0 otherwise.

For Example:

Suppose the script filename is addwarn.sh then,

echo "I am a string" > f1
echo "I am not a string > f2
./addwarn.sh "not" '*** WARNING ***'
cat f1 f2

I am a string
*** WARNING ***
I am not a string

What I have tried so far:

#! bin/sh

if [ $? -eq 0 ]; then
    exit

fi

if [ $? -ne 0 ]; then
    cat *
fi 

I am not sure how to make a script, any ideas?

Upvotes: 0

Views: 136

Answers (1)

Calvin Taylor
Calvin Taylor

Reputation: 694

#!/bin/sh
found=0

usage(){
    echo "$0 takes two args!"
    exit 4
} 

#check for two args
i=0
for a in "$@"; do
    ((i++))
done
[ "$i" -ne "2" ] && usage

uneditable=0
for f in $(find ./ -maxdepth 1 -type f); do
    if grep -q $1 $f ; then
        found=1
        echo -e "$2\n$(cat $f)" > $f || uneditable=1
    fi
done
[ "$found" = "0" ] && exit 1
[ "$uneditable" = "1" ] && exit 2
exit 0

Upvotes: 1

Related Questions