0

I have a sed script where the replacement string comes from user input, e.g.

echo -n "Enter identity? "
read identity
sed -i "s:^export identity=.*:export identity='$identity':g" $CFG_FILE

The problem is that the user may enter a value that has special meaning to sed, for example:

abc:abc

In this case, the colon character used in the sed statement, so causes an error.

Is there a way to allow the user to enter any value, but if a value has special meaning to sed then it gets escaped?


Note this question is similar to, but different from: https://stackoverflow.com/questions/23186445/escape-replacement-string-from-bash-source-file

Community
  • 1
  • 1
Chris Snow
  • 23,813
  • 35
  • 144
  • 309
  • 1
    What you are looking for is **sanatizing** inputs. http://stackoverflow.com/questions/89609/in-a-bash-script-how-do-i-sanitize-user-input – UnX Apr 20 '14 at 18:51

1 Answers1

1

Since you are using the variable in the replacement, you need to escape the character that represents the delimiter. Use shell parameter expansion:

identity="${identity//:/\\:}"

This would transform abc:abc into abc\:abc and abc:def:ghi into abc\:def\:ghi.

Moreover, you want to use:

read -r identity

instead. That would ensure that any backslashes in the user input do not escape any characters.

devnull
  • 118,548
  • 33
  • 236
  • 227