How do I sanitise user input in a bash script so that I can then pass it as an argument to another shell program? I want to prevent the following:
INPUT="filename;rm -rf /"
ls $INPUT
I was thinking it should be enough to surround the user input in double quotes like so:
ls "$INPUT"
but what if there is a double quote in $INPUT
?
Or does bash already deal with this problem?
The Short
Bash already deals with that. Quoting it is sufficient.
The Long
A rough guide to how the shell parses this line is:
Because of the quotes the
$INPUT
variable does not undergo word splitting. Thels
will look for a file namedfilename; rm -rf /
.If you didn't quote it then the expansion would proceed differently:
You can at least have consolation that this won't actually execute
rm -rf /
. Rather, it'll pass each of those strings as a file name tols
. You'llls
some files you didn't intend but at least it won't accidentally execute unwanted commands.Excerpts from "man bash":