How to prevent code/option injection in a bash script
Posted
by asmaier
on Stack Overflow
See other posts from Stack Overflow
or by asmaier
Published on 2010-06-10T08:44:31Z
Indexed on
2010/06/10
8:52 UTC
Read the original article
Hit count: 508
I have written a small bash script called "isinFile.sh" for checking if the first term given to the script can be found in the file "file.txt":
#!/bin/bash
FILE="file.txt"
if [ `grep -w "$1" $FILE` ]; then
echo "true"
else
echo "false"
fi
However, running the script like
> ./isinFile.sh -x
breaks the script, since -x
is interpreted by grep
as an option.
So I improved my script
#!/bin/bash
FILE="file.txt"
if [ `grep -w -- "$1" $FILE` ]; then
echo "true"
else
echo "false"
fi
using --
as an argument to grep. Now running
> ./isinFile.sh -x
false
works. But is using --
the correct and only way to prevent code/option injection in bash scripts? I have not seen it in the wild, only found it mentioned in ABASH: Finding Bugs in Bash Scripts.
© Stack Overflow or respective owner