I am writing a bash validation function that sanitizes user input.
The idea is that if a script has 3 parameters, those could be only alpha-numeric values. BUT a parameter could be multiple words enclosed in double quotes like so:
myfunction arg1 arg2 "this is arg3"
So I am basically looking to strip everything out that is not an alpha-numeric or space character.
At the moment, i've got:
validateEntry() {
string=$1
clean=${string//[^a-zA-Z0-9\s]/}
}
But it does not seem to work. In myfunction arg1 arg2 "this is arg3"
, the is arg3
is getting stripped out.
And the way I am using this function is in a script, like so:
name=$(validateEntry $1)
I need help with that.
The idea is to use the validateEntry
function in a script that can take, let's say, 3 arguments, like so:
if [[ "$#" -eq 3 ]]; then
arg1=$(validateEntry $1)
arg2=$(validateEntry $2)
arg3=$(validateEntry $3)
echo "${arg1}, ${arg2}, ${arg3}."
fi
But if my script's third argument is this is arg3
, $arg3
is reduced to this
, even though when i call my the function directly, with the same three arguments, the third arg is this is arg3
\s
does not mean "any type of whitespace" in a pattern (which is not a regular expression). Instead, either use just a literal space
clean=${1//[^a-zA-Z0-9 ]}
or, if you want to match spaces, tabs, newlines, etc, use the POSIX character class [:space:]
:
clean=${1//[^a-zA-Z0-9[:space:]]}
(For that matter, you can use character classes for the letters and numbers as well:
clean=${1//[^[:alnum:][:space:]]}
)
Once you've done that, there are two other things you need to change:
You need to actually output the cleaned-up value:
validateEntry () {
echo "${1//[^[a[:alnum:][:space:]]}"
}
You need to quote the expansion you want to validate, so that the entire thing is passed to your function:
name=$(validateEntry "$1")
Edited to match the question.
function validateEntry {
echo ${1//[^[:alnum:][:space:]]/}
}
if [[ $# -eq 3 ]]; then
echo $(validateEntry "$1")
echo $(validateEntry "$2")
echo $(validateEntry "$3")
fi
Command
./test.sh arg1 arg2 "this is arg3"
Output:
arg1
arg2
this is arg3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With