Tuesday, October 13, 2009

Brace {} in shell script

- Brace is used for expansion. If several words are separated by commas and surrounded by brace then in case of expansion the word/words before the brace is added to each word/words within brace and the word after the brace is suffixed to each word/words within the brace.

Following is an example of appending "Arju" keyword to each words within brace at first and " always." keyword appends to each words within brace at last.

$ echo 'Arju '{'GoodBoy','Goes to university','Works'}' always. '
Arju GoodBoy always. Arju Goes to university always. Arju Works always.

- With combination of brace and and cat command we can concatenate several files contents into one. Following is an example.

$ cat >file1.txt
one

$ cat >file2.txt
two

$ cat >file3.txt
three

$ cat {file1.txt,file2.txt,file3.txt} >file5.txt

$ cat file5.txt
one
two
three

- We can take facility of brace expansion while move or copy or rename files. For example the following can be used to rename a .txt file to .bak file.

$ cat file5.txt
one
two
three

$ mv file5.{txt,bak}

$ cat file5.bak
one
two
three

- Note that no spaces are allowed within the braces unless the spaces are quoted or escaped.

- With double dot we can use extended brace expansion construction which is a feature introduced in version 3 of Bash.

Example:

$ echo {a..m}
a b c d e f g h i j k l m

$ echo {5..10}
5 6 7 8 9 10


- The {} double curly brackets are a placeholder for output text. For example, curly brackets are placeholder for the path name output by "find".

DELETE_DIR=/home/arju/junk
find "$DELETE_DIR" -type f -atime +30 -exec rm {} \;

The above script deletes the files from "/home/arju/junk" that have not been accessed in at least 30 days (plus sign ... +30).
where,
-type indicates filetype", and
f = regular file

Related Documents

1 comment:

  1. More succinctly,

    cat {file1.txt,file2.txt,file3.txt} >file5.txt

    can be rewritten as

    cat file{1,2,3}.txt > file5.txt

    ReplyDelete