Bash User Input Validation
If you are writing your latest and greatest Bash shell script that requires careful user input, then you are probably looking for a way to validate or sanitize the input before using the data in commands or subroutines. Here’s an example shell script that reads user input into a variable, which we in turn echo and sanitize into a new variable. The new variable will then be used to perform whatever function is required, in this case displaying the new value.
#!/bin/bash read -p "Enter variable: " VAR_INPUT # Sanitize input and assign to new variable export VAR_CLEAN="`echo "${VAR_INPUT}" | tr -cd '[:alnum:] [:space:]'`" echo "New Variable: ${VAR_CLEAN}" |
Notice, we use the tr command to delete everything except alphanumeric and space characters. You can also perform further manipulation with any other command that comes to mind. For example, if you would like to also limit the number of characters to 10, use the cut command.
export VAR_CLEAN="`echo "${VAR_INPUT}" | tr -cd '[:alnum:] [:space:]' | cut -c -10`" |
I like using tr in this fashion, because instead of trying to exclude specific characters, you have the option to enforce a deny all policy, making it easier for you to allow only what you want.
As one of our readers mentioned, there is an even simpler method using only Bash search and replace! This eliminates the need for the execution of tr. In the following example, we sanitize the input allowing for only alphanumeric characters and spaces. I also show how to trim the string length to a maximum character limit of 10.
#!/bin/bash read -p "Enter variable: " VAR_INPUT # Sanitize input and assign to new variable export VAR_CLEAN_1="${VAR_INPUT//[^a-zA-Z0-9 ]/}" echo "New Variable 1: ${VAR_CLEAN_1}" # Sanitize input, assign to new variable but limit it to 10 characters export VAR_CLEAN_2="`echo "${VAR_INPUT//[^a-zA-Z0-9 ]/}" | cut -c -10`" echo "New Variable 2: ${VAR_CLEAN_2}" |
For more information, be sure to check out the man pages for tr and take a look at the Advanced Bash-Scripting Guide. Additional comments and ideas welcome!