Reputation: 45
I want to validate a file name in bash to make sure that I don't have this '[]' character in it
I have this :
if ! [[ $filename=~ ^[a-zA-Z]+$ ]]; then
echo 'Wrong filename input' >&2
exit 1
fi
but I want explicitly avoid [] and allow other special characters.
any advice?
Thanks.
Upvotes: 0
Views: 1052
Reputation: 785651
Use spaces around =~
operator:
[[ ! "$filename" =~ ^[a-zA-Z]+$ ]] && echo "bad filename" || echo "its good"
OR your own script:
if [[ ! "$filename" =~ ^[a-zA-Z]+$ ]]; then
echo 'Wrong filename input' >&2
exit 1
fi
Update:
If you want to explicitly avoid only [
and ]
then following check is better:
if [[ "$filename" == *[]\[]* ]]; then
echo 'Wrong filename input' >&2
exit 1
fi
Upvotes: 5