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

前端 未结 6 1079
抹茶落季
抹茶落季 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:48

    For Bash >= 4.0:

    CLEAN="${STRING//_/}" && \
    CLEAN="${CLEAN// /_}" && \
    CLEAN="${CLEAN//[^a-zA-Z0-9]/}" && \
    CLEAN="${CLEAN,,}"
    

    This is especially useful for creating container names programmatically using docker/podman. However, in this case you'll also want to remove the underscores:

    # Sanitize $STRING for a container name
    CLEAN="${STRING//[^a-zA-Z0-9]/}" && \
    CLEAN="${CLEAN,,}"
    

提交回复
热议问题