Path name expansion

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← Recalling command historyHomeCreate and use aliases →
  • Bash shell support path name expansion using the following techniques.

Curly braces

  • A curly braces ({..}) expands to create pattern and syntax is:
{ pattern1, pattern2, patternN }
text{ pattern1, pattern2, patternN }
text1{ pattern1, pattern2, patternN }text2
command something/{ pattern1, pattern2, patternN }
  • It will save command typing time.
  • Arbitrary strings may be generated.

Examples

Create a string pattern:

echo I like {tom,jerry}

Sample outputs:

I like tom jerry

A string is created, however this can be used to create unique file names:

echo file{1,2,3}.txt

Sample outputs:

file1.txt file2.txt file3.txt

OR

echo file{1..5}.txt

Sample outputs:

file1.txt file2.txt file3.txt file4.txt file5.txt

The filenames generated do not need to exist. You can also run a command for every pattern inside the braces. Usually, you can type the following to list three files:

ls -l /etc/resolv.conf /etc/hosts /etc/passwd

But, with curly braces:

ls /etc/{resolv.conf,hosts,passwd}

Sample outputs: To remove files called hello.sh, hello.py, hello.pl, and hello.c, enter:

rm -v hello.{sh,py,pl,c}

Another example:

D=/webroot
mkdir -p $D/{dev,etc,bin,sbin,var,tmp}

Wildcards

  • Bash supports the following three simple wildcards:
    1. * - Matches any string, including the null string
    2. ? - Matches any single (one) character.
    3. [...] - Matches any one of the enclosed characters.

Examples

To display all configuration (.conf) files stored in /etc directory, enter:

ls /etc/*.conf

To display all C project header files, enter:

ls *.h

To display all C project .c files, enter:

ls *.c

You can combine wildcards with curly braces:

ls *.{c,h}

Sample outputs:

f.c  fo1.c  fo1.h  fo2.c  fo2.h  fo3.c	fo3.h  fo4.c  fo4.h  fo5.c  fo5.h  t.c

To list all png file (image1.png, image2.png...image7.png, imageX.png), enter:

ls image?.png

To list all file configuration file start with either letter a or b, enter:

ls /etc/[ab]*.conf
← Recalling command historyHomeCreate and use aliases →