I have gone through tons of SO questions and google searches and cant find the answer to this one. I have a sed command that, when run in my bash script fails, but works fine from command line. I know it must be some wierdness with bash, but cant find what.
Script as follows :
#!/bin/bash
SEARCH=$1
REPLACE=$2
FILE=$3
SED="sed -i 's~$SEARCH~$REPLACE~g' $FILE"
echo "Running $SED"
$SED
Have also tried instead of the last $SED
line:
OUT=`$SED`
echo "Command output : $OUT"
but both versions give the following output when called with
# vmSub 'DOMAIN' 'example' mysql.sql
Running sed -i 's~DOMAIN~example~g' mysql.sql
sed: -e expression #1, char 1: unknown command: `''
Command output :
But copy/paste the echoed command works :
# sed -i 's~DOMAIN~example~g' mysql.sql
#
It doesn't matter if the search string is in the file or not. Have tried using '/' as the separator in the sed command, same result. As I am just copy/pasting the command as echoed out by the script, then I know what I test via command line SHOULD match what is executed by the bash script. Have also ensured that none of the options passed to the script contain special characters or spaces, so i know its not that causing the problem.
Am running on Linux RHEL with GNU bash, version 4.2.46(2)-release and sed (GNU sed) 4.2.2 have also confirmed that my interactive shell is /bin/bash
SOLVED : As per @thatotherguy in comments below, the answer was to move the bash vars outside the quotes, so the code now reads :
SED="sed -i 's~"$SEARCH"~"$REPLACE"~g' "$FILE
This now seams to work.
Thanks everyone for your help.