1

I have several bash scripts which read arbitrary strings (usually from stdin). When those strings contain things that bash recognizes, then things break.

For example, I have a simple logging script (named al) whose main function is to take an input string and write it to a file with a timestamp in front of it.

If I give it things like

al that didn't work

or

al I tried a & B

it breaks because bash sees the quote or ampersand (or other metacharacter) and tries to process it before it even gets to my script.

I would like to have a way to accept the string and run it through a filter to get rid of or add escapes ("\") to all the characters that may cause problems before I pass the string to the rest of my script.

I wrote a small C program to do it - letting it read the raw input, so bash never sees it. It works, but I don't really want to reinvent the wheel.

I know I can just input the strings manually with the characters escaped, but I usually forget to do that and sometimes they get stripped later anyway.

al I tried a \& b
al It didn\'t work

Is there some utility or a way to do this without writing it from scratch?

Joe
  • 351
  • 2
  • 16

1 Answers1

2

Are you trying to supply the arbitrary string on the command line, or as input (via stdin) after the script starts? If you're trying to provide it on the command line, you cannot do what you are trying to (in a script, C program, anything) because the shell always parses the command line by its own rules before your program even gets started.

If you're trying to read it as input after the script starts, it's fairly easy to do with the read command, although there are a couple of tricks to get properly "raw" input. Use something like:

IFS= read -r -p "Enter the string: " str

The IFS= part prevents it from trimming whitespace; -r prevents it from interpreting escapes. -p "Enter the string: " is an optional nicety, feel free to leave it off if appropriate.

(BTW, since IFS= is used as a prefix to the read command, it only applies to that one command, and does not have to be set back to normal afterward.)

Note that when using the variable (str in this case), you should always enclose it in double-quotes (e.g. echo "$str") to keep the shell from doing any parsing of its contents at that point. Actually, you should almost always double-quote shell variables anyway -- the number of shell script questions we get here where the solution is "double-quote your variables" is rather scary.

Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151