Reputation: 772
I am trying to replace some strings in a file with sed and I'm getting a strange error.
Here is the script...
#!/bin/bash
TEMPLATE=/etc/nginx/site-template
if [ -f $TEMPLATE ]; then
echo -n
else
echo "Template $TEMPLATE not found."
exit
fi
function usagehelp {
echo "Usage: DOMAIN SITEDIR"
echo "Example: createsite.sh test.com /var/www/sites/site"
}
if [ -z $1 ]; then
usagehelp
exit
fi
if [ -z $2 ]; then
usagehelp
exit
fi
SDOMAIN=$1
SDIR=$2
if [ -f /etc/nginx/sites-enabled/$SDOMAIN ]; then
echo "Site already exists!"
exit
fi
SCONFIG=/etc/nginx/sites-enabled/$SDOMAIN
cp $TEMPLATE $SCONFIG
sed -i -e "s/%DOMAIN%/$SDOMAIN/g" $SCONFIG
sed -i -e "s/%SITEDIR%/$SDIR/g" $SCONFIG
mkdir $SDIR
chown john:www-data $SDIR
chmod a-rwx,u+rwx,g+rx $SDIR
if nginx -t; then
nginx -s reload
echo "nginx reloaded with new site"
fi
Running it produces the following output, and I'm not quite sure why. I really need an extra set of eyes...
sed: -e expression #1, char 14: unknown option to `s'
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
nginx reloaded with new site
Upvotes: 0
Views: 228
Reputation: 295815
In the case of %SITEDIR%
, if your $SDIR
contains a directory name, then the first /
in the name will be seen as the end of the s///
command, rather than as data.
The bad answer is to try to pick a sigil which won't likely be in the filename -- for instance, if you don't expect the @
sign to be in a filename, use:
sed -i -e "s@%SITEDIR%@$SDIR@g"
The good answer is to use a completely different tool -- awk, perl, etc. There's an awk script which does this safely in BashFAQ #21.
Upvotes: 4