How to write RegEx in Shell Script to fail the script with exit code 1 if any of the input parameters contain possible shell injection commands. One or two examples are sufficient. Plz help.
Here is the code snippet:
invalid_format="^.*[;&|].*$"
invalid_format2="rmdir"
if [ "$LOCAL_DIR" =~ "$invalid_format" -o "$LOCAL_DIR" =~ "$invalid_format2" ];
then
echo "Error! LOCAL_DIR cannot contain command chaining characters like ; && ||"
exit 1
fi
but, it fails with the error:
[: too many arguments
Use grep
and pipe your string into grep
, then check the return value.
#!/bin/bash
STRING_TO_CHECK="abc"
REGEX="b"
echo "$STRING_TO_CHECK" | grep -E "$REGEX"
if [ $? -eq 1 ]
then
# regex not found
else
# regex found
fi
Thanks Everyone.. here I got this get done.
invalid_format="(^.[;&|].$)|(\brmdir\b)|(\bls\b)|(rm\s-)|(\bping\b)"
if [[ $LOCAL_DIR =~ $invalid_format ]]; then
echo "Error! LOCAL_DIR cannot contain command chaining characters like ; && || or possible shell injection commands"
exit 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.