jeudi 4 mai 2017

Bash compare two elements but perform the statement anyway

Why the statement here is performed anyway? I'd like create like a switcher to change the file host in local without changing manually whatever I need to go on live site. The problem is that when I use the -g option in the script, it must compare whether ther is already a # in front of the site name and exit without changing anything. I used it outside the script and it works it return a # if there is in the hosts, but as I said it performs anyway the statment.

#!/bin/bash
  if [ "$1" = "-l" ]; then
    sed -i.bak --regexp-extended "s/#(127.0.0.1\s+$2)/\1/" /etc/hosts
    sed -i.bak --regexp-extended "s/#(127.0.0.1\s+www\.$2)/\1/" /etc/hosts
  elif [ "$1" = "-g" ]; then
      if [ "$(cat hosts | grep -P  "#127.0.0.1\s+$2" | grep -o "#")"="#" ] || [ "$(cat hosts | grep -P  "#127.0.0.1\s+www.$2" | grep -o "#")"="#" ]
        then
        exit
      else
        sed -i.bak --regexp-extended "s/127.0.0.1\s+$2/#&/" /etc/hosts
        sed -i.bak --regexp-extended "s/127.0.0.1\s+www.$2/#&/" /etc/hosts
      fi
  else
    echo "Syntax of use: virtualhost [-l] [-g] domain_name"
  fi

Aucun commentaire:

Enregistrer un commentaire