How to prevent code / option injection in bash script

I wrote a small bash script called "isinFile.sh" to check if the first term specified in the script in the file.txt file can be found:

#!/bin/bash

FILE="file.txt"

if [ `grep -w "$1" $FILE` ]; then 
 echo "true"
else
 echo "false"
fi

However running the script as

> ./isinFile.sh -x

breaks the script, as it is -xinterpreted grepas 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 --grep as an argument. Now run

> ./isinFile.sh -x
false

works. But uses the --correct and only way to prevent code / option input in a bash script? I did not see it in the wild, I only found it in ABASH: search for errors in bash scripts .

+3
source share
3
grep -w -- ...

-

( ). , . - ; ".{0}-x" , ., ,

grep -w ".{0}$1" ...

.

+2

( -, ) script: grep [ (aka test) , ' , . , [ . , , 0 -eq 2, "0" - [, , 0 2, script false, , .

- - ( ) - , ( -q grep ). , : if [ "$(grep -w -- "$1" "$FILE")" ]; then ( , $() backquotes, , $ - , , ).

+2

, , , , - :

rm ./-x

rm /path/to/-x
+1

Source: https://habr.com/ru/post/1749361/


All Articles