Shell tricks
We will learn about two shell features that can save you a lot of typing.
Expansion
command PREFIX{aaa,bbb}POSTFIX
is expanded to command PREFIXaaaPOSTFIX PREFIXbbbPOSTFIX
.
It also works with more than two arguments inside the curly brackets {}
.
This is especially useful when dealing with paths. Here are some examples:
mkdir -p dir/sub{1,2,3}
➡️mkdir -p dir/sub1 dir/sub2 dir/sub3
touch dir/sub1/file{1,2}.txt
➡️touch dir/sub1/file1.txt dir/sub1/file2.txt
cp dir/sub1/file1.txt{,.bak}
➡️cp dir/sub1/file1.txt dir/sub1/file1.txt.bak
Note: The additional extension
.bak
is sometimes used for backups.
Globbing
The globbing asterisk *
is used for expanding to every possible path in a directory.
It is best explained using examples:
cat *.sh
prints the content of all files ending with.sh
in the current directory.mv dir1/* dir2
moves all visible files and directories fromdir1
todir2
.mv dir1/.* dir2
moves all hidden files and directories fromdir1
todir2
.mv dir1/{,.}* dir2
expands tomv dir1/* dir1/.* dir2
and therefore moves all visible and hidden files and directories fromdir1
todir2
.
Note: Fish can expand a globbing when pressing
Tab
after an asterisk*
(but it is not always helpful).