Wednesday, November 25, 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 "Vision" keyword to each words within brace at first and " always." keyword appends to each words within brace at last.

$ echo 'The '{'Virtual','only'}' Vision. '
The Virtual Vision.  The only Vision.

- 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/test/junk
find "$DELETE_DIR" -type f -atime +30 -exec rm {} \;

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

Thanks & Regards,
Anto Joe Natesh I

No comments: