In a bash script, how do I sanitize user input?

前端 未结 6 1049
抹茶落季
抹茶落季 2020-12-24 05:01

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-alph

6条回答
  •  时光说笑
    2020-12-24 05:41

    Bash can do this all on it's own, thank you very much. If you look at the section of the man page on Parameter Expansion, you'll see that that bash has built-in substitutions, substring, trim, rtrim, etc.

    To eliminate all non-alphanumeric characters, do

    CLEANSTRING=${STRING//[^a-zA-Z0-9]/}
    

    That's Occam's razor. No need to launch another process.

提交回复
热议问题