Tag Archives: Issue Alright

[Help] Grep, Variables, IF statements… Fun

By JonLaberge

Hello, this will be my first post. I’ve been browsing around for a bit and have found a lot of useful information on here, hopefully a solution can be provided to me.

Issue:

Alright, I am looking to search for strings within a file using variables.

I have a script that will accept 3 or 4 parameters, 3 is required 4th isn’t mandatory.

I would like to search the text file for the 3 parameters matching within the same line, if they do match then I want to remove that line and replace it with my new one, basically it would update the 4th parameter if set, and avoid duplicate entries.

Currently this is what I have gotten:

input= egrep -e ‘$domains+$types+$item’ ~/etc/security/limits.conf

if [ “$input” == “” ]; then

echo $domain $type $item $value >>~/etc/security/limits.conf

echo “$domain” “$type” “$item” “$value” has been successfully added to your limits.conf file.

else
cat ~/etc/security/limits.conf | egrep -v “$domain|$type|$item” >~/etc/security/limits.conf1
rm -rf ~/etc/security/limits.conf
mv ~/etc/security/limits.conf1 ~/etc/security/limits.conf

echo $domain $type $item $value >>~/etc/security/limits.conf

echo “$domain” “$type” “$item” “$value” has been successfully added to your limits.conf file.
exit 0
fi

Now I already know that the input=egrep etc.. will not work, it works if I hard code some values but it won’t accept that variables. Basically I have domain=$1, type=$2 and so on.

I would like it so that if all 3 variables are not matched within ONE line, than it will just append the parameters to the end of the file, BUT if the parameters do match then I want them to be deleted. and appended to the file. I know I can use other things like sed and awk, but I have yet to learn it, I don’t mind learning how to use other commands if there’s any express lessons that could be given to me for this instance before I start learning them in class.

This is for a school assignment, and all help is very much appreciated, but I’d also like to learn why and how it works/doesn’t so if you can provide answers to that as well that would be great !

Not quite sure if my “if statement” used to decide between if the parameters exist or not is even that strong or good, but I am new to programming, scripting “bashing” so I welcome all constructive criticism

Thank you,
Jon

…read more
Source: FULL ARTICLE at The UNIX and Linux Forums