Link to home
Start Free TrialLog in
Avatar of atom_jelly
atom_jellyFlag for United States of America

asked on

if and sed statement

I am trying to build a script and need some help with the if statement checking if the file exists and if true check for the string and if not true add string and to file with sed.

For example check for the /etc/inittab file and search for password string then if not there use sed to put in my password string into file.
Avatar of woolmilkporc
woolmilkporc
Flag of Germany image

1)

Check for existence of a file:

if [ -e /etc/inittab ]; then
...
fi

"man test" is very useful here.

2)

Search for a string:

grep "password" filename

Within an "if" construct, this time checking for non-existence of the string:

if ! grep -q "password" filename ; then
...
fi

3)

Replace a string with sed:

sed 's/oldstring/newstring/' filename > filename.new

or (in place, if supported)

sed -i 's/oldstring/newstring/' filename

Please explain "put in my password string into file", because how to achieve this  heavily depends on the file format.
Avatar of atom_jelly

ASKER

Here is my template but I invite you to simplify it. Thanks.

#!/bin/bash

file="test"
string="password"

if [ -f "$file" ]

then

echo "$file exists"

else

if ! grep -q "$string" "$file";

then

echo "$string does not exist in $file file"
sed -i -e '4a\
password --md5 $1$abcdefghijklmno.' "$file"

fi
   fi
ASKER CERTIFIED SOLUTION
Avatar of woolmilkporc
woolmilkporc
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you for the quick reply.