Bash - pathname expansion (Filename expansion)

About

pathname or filename expansion 1) is an expansion (code replacement at runtime) that replaces globbing wildcard by pathname.

The path name in this context is the last part in a path, it is therefore equivalent to the file name

Example

Asterisk

The asterisk character matches every filename in a given directory.

Example: The examples have the following files in their current directory

foo.txt
bar.txt

Example 1

The following echo command

echo * 

will expand to all files in the current directory and will be equivalent at runtime to the following command

echo foo.txt bar.txt

and will effectively list all files in the current directory

foo.txt bar.txt



Example 2 The following echo command

echo b* 

will expand to all files that starts with a b in the current directory and will be equivalent at runtime to the following command

echo bar.txt

listing only the bar file

bar.txt

Question Mark

  • ? matches a single character
echo t?.sh # will list the file that start with t and have two characters

If there is no match, the expression is just echoed

Double Asteriks

The globstar parameters should be set to enable Glob - Globbing (Wildcard expression)

shopt -s globstar
ls **/
shopt -u globstar
ls **/

If followed by a /, two adjacent *s will match only directories and subdirectories.

Braces

braces globbing is supported on the last bash version

ls -l {b*,c*,*est*}

Not to confound with brace expansion that generates string.

Documentation / Reference

More on globbing pathnames or

man 7 glob | col -b > glob.txt

Powered by ComboStrap