面试题答案
一键面试输入处理方法
- 字符转义:对特殊字符进行转义,比如
&
转义为&
,<
转义为<
,>
转义为>
,"
转义为"
,'
转义为'
等。在Bash中可使用工具或自定义函数来实现。 - 过滤非法字符:只允许特定字符集,比如字母、数字、特定符号等。可以使用正则表达式在Bash中过滤。例如,只允许字母和数字:
input=$(echo $input | grep -oE '[a-zA-Z0-9]+')
。 - 长度限制:限制输入长度,避免超长输入可能带来的风险。在Bash中可以通过获取字符串长度判断并截取。例如:
max_length=100
if [ ${#input} -gt $max_length ]; then
input=${input:0:$max_length}
fi
Bash环境下可能用到的函数或工具
- sed:流编辑器,可用于文本替换和转换。例如,对特殊字符转义:
input=$(echo $input | sed 's/&/&/g; s/</</g; s/>/>/g; s/"/"/g; s/'\''/'/g')
。 - grep:用于文本搜索,结合正则表达式过滤非法字符。如上述过滤字母数字示例。
- 自定义函数:可以编写函数封装处理逻辑,提高代码复用性。例如:
sanitize_input() {
local input=$1
input=$(echo $input | sed 's/&/&/g; s/</</g; s/>/>/g; s/"/"/g; s/'\''/'/g')
input=$(echo $input | grep -oE '[a-zA-Z0-9&;]+')
max_length=100
if [ ${#input} -gt $max_length ]; then
input=${input:0:$max_length}
fi
echo $input
}
然后调用函数:clean_input=$(sanitize_input "$user_input")
。