0

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?

7
  • Why are you trying to check $? in your script? Commented Nov 6, 2017 at 0:44
  • I was trying to get exit status Commented Nov 6, 2017 at 0:56
  • Exit status of what? Commented Nov 6, 2017 at 0:56
  • Of the last command to get zero value, but it seems pretty much wrong. Commented Nov 6, 2017 at 1:01
  • 1
    What last command? What does any of this have to do with the task described in your first paragraph? Commented Nov 6, 2017 at 1:01

1 Answer 1

1
#!/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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.