在bash脚本,我如何过滤用户输入? [英] In a bash script, how do I sanitize user input?

查看:144
本文介绍了在bash脚本,我如何过滤用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找采取简单的输入的最佳方式:

I'm looking for the best way to take a simple input:

echo -n "Enter a string here: "
read -e STRING

和除去非字母数字字符,更低的(情况),并用下划线代替空格清理。

and clean it up by removing non-alphanumeric characters, lower(case), and replacing spaces with underscores.

请问为了此事?为 TR 去了解这一点的最好/唯一途径?

Does order matter? Is tr the best / only way to go about this?

推荐答案

由于dj_segfault指出,外壳可以做这个最适合你。看起来你将不得不求助于外部的东西对低套管串,虽然。对于这个你有很多选择,比如Perl的上述单行等等,但我觉得TR可能是最简单的。

As dj_segfault points out, the shell can do most of this for you. Looks like you'll have to fall back on something external for lower-casing the string, though. For this you have many options, like the perl one-liners above, etc., but I think tr is probably the simplest.

# first, strip underscores
CLEAN=${STRING//_/}
# next, replace spaces with underscores
CLEAN=${CLEAN// /_}
# now, clean out anything that's not alphanumeric or an underscore
CLEAN=${CLEAN//[^a-zA-Z0-9_]/}
# finally, lowercase with TR
CLEAN=`echo -n $CLEAN | tr A-Z a-z`

下面的顺序是比较重要的。我们想摆脱下划线,加用下划线代替空格,所以我们必须确保剥离强调第一。通过等待传递的东西TR才结束,我们知道我们只有字母,数字和下划线,而且我们可以肯定我们没有空间,所以我们不必担心特殊字符是由shell PTED间$ P $

The order here is somewhat important. We want to get rid of underscores, plus replace spaces with underscores, so we have to be sure to strip underscores first. By waiting to pass things to tr until the end, we know we have only alphanumeric and underscores, and we can be sure we have no spaces, so we don't have to worry about special characters being interpreted by the shell.

这篇关于在bash脚本,我如何过滤用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆