Bash - escape all special characters in variable string?
I have the following script (test.sh):
Code:
#!/bin/bash ./test.sh * It produces: - Code:
LINE: test.sh I've tried: - printf "%q\n" "LINE: ${INPUT}" and printf "%b\n" "LINE: ${INPUT}" None of which work. I just want it to print any special characters within the variable $INPUT as a String. Can it be done? |
The problem isn't the script, it's shell expansion at work. The shell expands the asterisk to all file names in the current directory before passing it to the script.
Try: ./test \* |
Or try surrounding the input in single quotes so the shell does not interpret any special characters
|
Try this:
PHP Code:
|
Hi,
I realise that I could do Code:
./test.sh \* Code:
INPUT='$1' Thank you for the theory as to why I'm getting the contents of the directory though - I didn't know about shell expansion :) |
Quote:
Code:
./test.sh * Code:
./test.sh file1 file2 file3 file4 etc... The only way you can pass a raw globbing value is to escape or quote the arguments that you want to pass to the shell on the command line, or to disable globbing in the parent shell. This is true of all shell syntax. If there's anything that's considered important by the shell on the line, it will be parsed and replaced before the command is run, unless it's protected by quotes or backslash escapes. Edit: BTW, once a value is stored in a variable or parameter, all the characters in the string are literal, and they will be treated as such by the script as long as you properly quote it. Only unquoted parameters are ever parsed for shell-reserved characters (unless you use a specific command option like printf's "%b" or echo's "-e" to force it to interpret them). So your only real problem is with the initial setting of "$1", and how you quote it afterwards. How about showing us exactly what you need to do, rather than fooling around with an example that may not reflect your actual purpose? |
Hi!
I gave you the working example above but you do not seem to check it out. Here is a script, if scrip is the only way to make you understand, that does what you expect regarding Shell Expansion: Code:
[demo@devhost Bash]$ cat rubbish.sh If you think each character/word is to be taken as a separate parameter inside your script then you can simply split the line (PARA=$1) to work with them. That is your homework to learn more. |
Ah, sorry - misread. Many thanks, that fixed it. No need to be quite so snide about it, tho :)
|
Okay, since I'm also doing: -
Code:
echo $LINE >> SOME_FILE.tmp # won't work Code:
set -f |
Or you could put double quotes around $LINE
|
Quote:
|
All times are GMT -5. The time now is 03:08 AM. |