I am attempting to use a regular expression within a Bash conditional expression and Bash does not like my syntax. The code follows:
declare -a sshkeys
declare sshpath="$HOME/.ssh"
if [[ -f "$sshpath/ssh_keys" ]]; then
mapfile -t sshkeys <"$sshpath/ssh-keys"
fi
declare pattern="^(:alnum::alnum:*)(:blank:|#|$)"
for i in {"$sshkeys[@]"}
do
if [[ [ "$i" ~= "$pattern" ] && [ -e "$sshpath/$BASH_REMATCH[1]" ] ]]; then
ssh-add "$sshpath/$BASH_REMATCH[1]" </dev/null 1>&-
fi
done
Bash produces the following error message:
source .profile
bash: .profile: line 49: conditional binary operator expected
bash: .profile: line 49: syntax error near `"$i"'
bash: .profile: line 49: ` if [[ [ "$i" ~= "$pattern" ] && [ -e "$sshpath/$BASH_REMATCH[1]" ] ]]; then'
It looks like Bash is not happy with regular expression tests in complex conditional expressions. Can anyone say how I should be doing this?