Bash brace expansion to expand arguments
In Category Bash
Braces can be used to expand arguments in bash. Bash expands a list of strings separated by commas with in braces to a list of strings separated by spaces. Look at the simple example below:
[neo@techpulp ~]# echo {red,green,white}
red green white
[neo@techpulp ~]#
The above example may not be really useful but you can use bash to expand the arguments by adding prefix or suffix to the braces as shown below to generate expanded arguments. Note that there should not be any space between suffix/prefix and the start/end bracket. Otherwise it is considered as a separate list.
[neo@techpulp ~]# echo {red,green,white}ball
redball greenball whiteball
[neo@techpulp ~]#
Similarly you can add a prefix to the list of strings present in the braces.
[neo@techpulp ~]# echo light{red,green,white}
lightred lightgreen lightwhite
[neo@techpulp ~]#
You can add prefix and suffix together as well.
[neo@techpulp ~]# echo light{red,green,white}ball
lightredball lightgreenball lightwhiteball
[neo@techpulp ~]#
You can have two separate list of strings present in two braces attached together as shown below. You can see bash generating all possible permutations.
[neo@techpulp ~]# echo {ball,cat,rat}{red,green,white}
ballred ballgreen ballwhite catred catgreen catwhite ratred ratgreen ratwhite
[neo@techpulp ~]#
Now you may be wondering where this trick can be used in day to day work. Here is a list of examples:
Take backup of a file:
[neo@techpulp ~]# ls
exmaple.c
[neo@techpulp ~]# cp exmaple.c{,.bak}
[neo@techpulp ~]# ls
exmaple.c exmaple.c.bak
[neo@techpulp ~]#
Check the differences between two files.
[neo@techpulp ~]# ls
exmaple.c exmaple.c.org
[neo@techpulp ~]# diff exmaple.c{,.org}
14a15
> printf("i = %d\n", i);
[neo@techpulp ~]#
Recent Comments