Novice C
Novice C

Reputation: 1374

Shell: case switch with tuple argument

In the case of a tuple case switch, could you specific the glob for any of the variables in the tuple?


I am curious how the case switch works in specifically a bash shell, when the argument is a tuple. The example I'll use is the git-hook for prepare-commit-msg; however, I'll explain so no knowledge is required.

The arguments for the script are: $1=commit message, $2=commit type and $3=SHA-1. The commit message, $1, is irrelevant for our purposes. The commit type, $2, can be any of the following strings: message, template, merge, squash or commit. And the SHA-1, $3, is either a 40 char string or null.

The code distributed with git is

#!/bin/bash    

case "$2,$3" in 
  merge,)
    # do something for merge with no SHA-1
  ;;

  *)
   # do something for everything else
  ;;

If the answer to my question is yes, then is this the correct way of its implementation?

#!/bin/bash    

case "$2,$3" in 
  merge,)
    # do something for merge with no SHA-1
  ;;

  commit,*)
   # do something for commits with SHA-1
  ;;

  *,)
    # do something for non merge with no SHA-1
  ;;

  *,*)
    # do something for non commit with SHA-1
  ;;

Upvotes: 0

Views: 353

Answers (1)

gzh
gzh

Reputation: 3596

Quoted from manpage of bash.

A case command first expands word, and tries to match it against each pattern in turn, using the same matching rules as for pathname expansion (see Pathname Expansion below). The word is expanded using tilde expansion, parameter and variable expansion, arithmetic substitution, command substitution, process substitution and quote removal. Each pattern examined is expanded using tilde expansion, parameter and variable expansion, arithmetic substitution, command substitution, and process substitution.

I think your implementation is correct.

Upvotes: 1

Related Questions