Thursday, February 20, 2014

Explain: {,} in cp or mv Bash Shell Commands

I often see commands as follows posted on blog or forums
cp /etc/httpd/httpd.{,.bakup}
OR
mv resume{z,}.doc
What is the purpose of {,} in Linux and Unix shell commands?

{} is nothing but brace expansion and usually used to generate combinations. From the GNU/bash man page:
Brace expansion is a mechanism by which arbitrary strings may be generated. This mechanism is similar to filename expansion, but the file names generated need not exist. Patterns to be brace expanded take the form of an optional preamble, followed by either a series of comma-separated strings or a seqeunce expression between a pair of braces, followed by an optional postscript. The preamble is prefixed to each string contained within the braces, and the postscript is then appended to each resulting string, expanding left to right.
Open terminal and type the following command:
echo foo{1,2,3}.txt
Sample outputs:
foo1.txt foo2.txt foo3.txt
Try the following additonal examples to create arguments for commands and save typing time:
### I am using echo for demo purpose only ####
echo file.txt{,.bak}
echo file-{a..d}.txt
echo mkdir -p /apache-jail/{usr,bin,lib64,dev}
echo cp httpd.conf{,.backup}
echo mv delta.{txt,doc}
 
You can use brace expansion to copy file, rename/backup file, or create directories. In this traditional example, make a backup of a file named file1.txt to file2.txt.bak, type:
 
cp -v file1.txt file1.txt.bak
 
You can save time with brace expansion as follows:
 
cp -v file1.txt{,.bak}
 
Sample outputs:
file1.txt -> file1.txt.bak
See bash(1) command man page for more information.

0 comments:

Post a Comment