4

I want to run a bash command on output from Drupal's drush command-line interface. drush site-alias returns a list of webroots, first showing the name of the group, and then each site in that group. The site itself is aliased in the form group.site. For instance, you might get

internal internal.site1 internal.site2 external external.site1 external.site2 marketing marketing.site1 marketing.site2

I want to do a command on each of the site aliases, but not on the group alias itself. I need to test if the string has a period in it, and if so, run it:

for i in $(drush site-alias); do {if no period) drush $i command; done;

How can I run this test?

6

You can use pattern matching:

for i in $(drush site-alias) ; do
    if [[ $i == *.* ]] ; then
        drush "$i" command
    fi
done
5

With any Bourne-like shell, you'd write it:

case $i in
  *.*) drush "$i" command;;
esac
2

You can do this with a pattern replace expansion:

for i in $(drush site-alias); do
  if [ -z "${i//[^.]/}" ]; then
     # no period
     drush "$i" command
  fi
done

Yes, I quoted "$i", which is probably something you should do when possible, it avoids surprises. Though in this case it won't matter.

  • You don't have to quote it if you use [[ instead of [. You are already using non-POSIX features. – jordanm Feb 1 '13 at 23:54
  • 1
    @jordanm No, I mean I quoted it in the drush "$i" line. Which you should quote regardless of using [[ vs. [. – derobert Feb 2 '13 at 1:48
2

Just for the sake of another independent answer, I'm going to suggest using shell parameter expansions.

for i in $(drush site-alias)
do
    if [[ ${i%.*} == $i ]]
    then
        drush $i command
    fi
done
  • I don't see any advantage of this over [[ $i = *.* ]], which ksh (even ksh88) also understands and is markedly clearer and marginally faster. – Gilles Feb 1 '13 at 23:10
  • Like I wrote, just another answer: why leave something out, if stackexchange is to be a definitive Q&A site? – Bruce Ediger Feb 1 '13 at 23:41
  • That would return true for i='*' (in which case the missing quoted around $i in drush $i... would also be a problem (would be a problem in any case)). – Stéphane Chazelas Jul 30 '16 at 8:41
1

Using the =~ bash operator.

for i in $(drush site-alias); do
  if ! [[ $i =~  \. ]]; then
     drush "$i" command
  fi
done
  • 1
    Note that with bash-3.1 (or with bash -O compat31, or with zsh), you'd need [[ $i =~ \\. ]] or [[ $i =~ '\.' ]]. For compatibility between the versions, you can use a variable (dot='\.'; [[ $i =~ $dot ]]) or use [[ $i =~ [.] ]] – Stéphane Chazelas Jul 30 '16 at 8:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.