• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Daniel J. Barrett

  • Home
  • Books
    • Efficient Linux at the Command Line
    • Linux Pocket Guide
    • Linux Security Cookbook
    • Macintosh Terminal Pocket Guide
    • MediaWiki
    • SSH, the Secure Shell: The Definitive Guide
    • Translations
    • Out of Print
  • Blog
  • About
  • Contact

Commands, Linux, Shell · February 22, 2022

Brace expansion to reduce typing

Have you ever found yourself copying a Linux file and adding a suffix, like this?

$ cp myfile myfile2

Try this command instead, which does the same thing but with less typing (one argument instead of two):

$ cp myfile{,2}

Why it works: This command employs brace expansion, a feature of certain Linux shells. A comma-separated expression like this:

myfile{1,2,3}

expands to this:

myfile1 myfile2 myfile3

In my example command, the braces enclose two strings: an empty string and a 2.  So this expression:

myfile{,2}

expands to:

myfile myfile2

Throw a “cp” or “mv” command at the beginning, and you have the command I suggested:

$ cp myfile{,2}

which expands to:

$ cp myfile myfile2

I learned this empty-string trick from a colleague, Dan Ritter (thanks!), who recommends it when the original filename is very long, so you don’t have to type the name twice:

$ mv very_silly_long_file_name{,.old}

The preceding command expands to:

$ mv very_silly_long_file_name very_silly_long_file_name.old

You’ll find many more tips and techniques in my new book, Efficient Linux at the Command Line.

 

Filed Under: Commands, Linux, Shell

Daniel Barrett

Dan is the author of numerous books on technology, including the bestselling "Linux Pocket Guide" and the new "Efficient Linux at the Command Line."

Primary Sidebar

Efficient Linux at the Command Line
Buy: Amazon US • O'Reilly • Bookshop.org • Amazon CA • Amazon UK

Linux Pocket Guide

Buy: Amazon US • O'Reilly • Bookshop.org • Amazon CA • Amazon UK

Recent posts

  • Sharpen Your Linux Command-Line Skills with Spelling Bee Puzzles
  • Check for duplicate code with a one-liner
  • Brace expansion to reduce typing
  • Why I wrote “Efficient Linux at the Command Line”

RSS feed

RSS feed

Archives

  • October 2022
  • April 2022
  • February 2022

Copyright 2022 Daniel J. Barrett