Globbing

The glob command, short for global, originates in the earliest versions of Bell Labs' Unix.

 

Globbing is the process of carrying out filename expansion (i.e. expanding filename patterns) using special characters, namely the wildcards:

  • ? representing any single character
  • * representing zero or more characters

*

Matches any string, of any length

 

foo*

Matches any string beginning with foo

 

*x*

Matches any string containing an x (beginning, middle or end)

foo?

Matches foot or food but not fools

 

Filename expansion can also match dotfiles, but only if the pattern explicitly includes the dot as a literal character e.g. *.txt

Accordingly, a file starting with a dot will not be matched with a wildcard.

 

*.tar.gz

Matches any string ending with .tar.gz

 

Square brackets specify a range of characters to match one of any characters inside [...]

 

  • [abc]
    • matches either a, b or c, but not the string abc
    • *.[ch] matches anything ending with .c or .h
  • [a-c]
    • matches any character between (inclusive) a and c
    • similar to the above
  • [!a-c] or [^a-c]
    • The ! or ^ at the beginning tells Bash to invert the match
    • Therefore matches any other character that is not a, b or c

 

Curly braces specify terms separated by a comma. Spaces are not allowed after the commas, or anywhere else

 

This example will move anything ending with .txt or .doc to the user's home directory:

  • mv {*.txt,*.doc} ~