2

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" != "*[*" ]
guz4217
  • 41
  • 5
  • Looks like another answer on the first page you linked will help: https://stackoverflow.com/a/16263820/1354854. The solution is `if [[ $hostName != *"["* ]]`. The wildcard must be _outside_ the quotes, which is not intuitive, or just unquoted entirely since you're using `[[`. – bnaecker Sep 15 '17 at 05:11
  • Huh, did not see that one. OK that works, thanks a lot :) . – guz4217 Sep 15 '17 at 05:23

2 Answers2

0

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
John1024
  • 109,961
  • 14
  • 137
  • 171
0

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
drewster
  • 5,460
  • 5
  • 40
  • 50