问题
I am searching for a comparison with square brackes in bash.
Situation: I have a hosts file that contains hostnames that looks like
[debian]
ansible
host
names
[centos]
more
hosts
now I want to scan all host's ssh keys (first echo, later use ssh-keyscan):
while read hostName
do
if [[ $hostName != "" ]] && [[ $hostName != "\[*" ]] ; then
echo $hostName
#ssh-keyscan $hostName
fi
done < hosts
while [[ $hostName != "" ]]
does it's job the part containing the comparison for square brackets [[ $hostName
!= "\[*" ]]
does not. Atm the result looks like this:
[debian]
ansible
host
names
[centos]
more
hosts
I want it to look like:
ansible
host
names
more
hosts
While e.g. How to compare strings in Bash covers the general topic, it does not cover my question. Also I'd like to avoid using sed or other string replacement methods before I can compare the string -if possible. Does anybody know how to compare square brackets in a string in bash?
Also not working: this solution, adapted comparison (maybe I adapted it the wrong way?):
if [[ $hostName != "" ]] && [ "$hostName" != "*[*" ]
回答1:
This does what you need and is POSIX compatible:
while read hostName
do
if [ "$hostName" ] && [ "$hostName" = "${hostName#[}" ] ; then
echo $hostName
#ssh-keyscan $hostName
fi
done < hosts
回答2:
Alternative #1:
while read hostName
do
if [[ $hostName != "" ]] && [[ $hostName != *"["* ]] ; then
echo "$hostName"
#ssh-keyscan $hostName
fi
done < hosts
Alternative #2:
grep -v '^\[.*\]$' hosts | while read hostName
do
if [[ $hostName != "" ]] ; then
echo "$hostName"
#ssh-keyscan $hostName
fi
done
Alternative #3:
grep -v '^\[.*\]$' hosts | grep -v '^[ \t]*$' | while read hostName
do
echo "$hostName"
#ssh-keyscan $hostName
done
来源:https://stackoverflow.com/questions/46231965/how-to-compare-strings-containing-a-square-bracket-in-bash