Shell wildcards

The patterns *, ?, [abc], [a-z], [!abc] and braces, the hidden files that * skips, the fact that the shell expands patterns before running the command, and the role of quotes.

  • 23 cards
  • 5 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios
  5. Understand

A few cards from the deck

  • Wildcard *: what is it?

    Show the answer

    A pattern replaced by all the existing file names that match, with any run of characters (even empty) in its place.

    *.txt matches a.txt and final report.txt, but not .cache.txt: a name that starts with a dot must be written with its dot (.*).

  • A directory contains photo1.jpg, photo2.jpg, photo9.jpg, photo10.jpg and photo1.png. What does photo[1-9].jpg expand to?

    • photo1.jpg photo2.jpg photo9.jpg
    • photo1.jpg photo2.jpg photo9.jpg photo10.jpg
    • photo1.jpg photo2.jpg photo9.jpg photo1.png
    • photo1.jpg photo10.jpg
    Show the answer

    photo1.jpg photo2.jpg photo9.jpg

    The class [1-9] matches a single character: photo10.jpg has two between photo and .jpg, and photo1.png has the wrong extension.

  • Wildcards are expanded by the …, before the command is run: ls *.txt already receives the ….

    Show the answer

    Wildcards are expanded by the shell, before the command is run: ls *.txt already receives the list of names.

    echo *.txt shows what any command would see. The command cannot tell whether the user typed a wildcard or the names.

  • Wildcard ?: what is it?

    Show the answer

    A pattern that matches exactly one character, whatever it is.

    photo?.jpg matches photo1.jpg and photoA.jpg, but not photo10.jpg (two characters) nor photo.jpg (none).

  • In a directory with no .zip file, rm *.zip answers “rm: cannot remove '*.zip': No such file or directory”. What happened?

    • No name matched: bash left *.zip as is and rm looked for that literal name
    • The shell is not allowed to expand wildcards in this directory
    • The .zip files are hidden, so * never matches them
    • rm does not understand wildcards: you need find -name to delete
    Show the answer

    No name matched: bash left *.zip as is and rm looked for that literal name

    A pattern that matches nothing stays as is (bash's default behaviour). So rm sees the name *.zip and complains it does not exist: a file name can legitimately (but very rarely) contain a star.