Optimizing scripts execution time
1.Make directory trees in a single command
tired of time consuming:
~ $ mkdir tmp ~ $ cd tmp ~/tmp $ mkdir a ~/tmp $ cd a ~/tmp/a $ mkdir b ~/tmp/a $ cd b ~/tmp/a/b/ $ mkdir c ~/tmp/a/b/ $ cd c ~/tmp/a/b/c $ |
use the -p option to mkdir
~ $ mkdir -p tmp/a/b/c |
Or fore more complex directory trees
~ $ mkdir -p project/{bogdan/src,bin,doc/{html,Make,pdf},final/demo/1}
|
2. Manage long input
I like to edit my sources and scripts in vi. Sometimes the code tends to be long. So, for easy reading after, I put a backslash (\) that continues a long line over to the next line.
~ $ cd tmp/a/b/c || \ > mkdir -p tmp/a/b/c && \ > tar xvf -C tmp/a/b/c ~/archive.tar |
Because the shell always treats it as one continuous line, (it strips out all the backslashes and spaces)
3.Run commands in a subshell
To enclose my commands in a single group, I use parentheses and the commands run in a new subshell and allows redirection/collection of the output
~ $ ( cd tmp/a/b/c/ || mkdir -p tmp/a/b/c && \ > VAR=$PWD; cd ~; tar xvf -C $VAR archive.tar ) \ > | mailx admin -S "Archive contents" |
4.Run commands in the current shell
Sometimes, running in the current shell, could be a lot faster. Curly braces ({}) is to enclose commands to run in the current shell.
5.Piping – speed factor
Piping grep to wc -l in order to count the number of lines of output is slower than the -c option to grep gives a count of lines that match the specified pattern
When inserting multiple files, grep with the -c option returns a separate count,one on each line,for each file; a pipe to wc gives a total count for all files combined.
6.Piping cats
When I’ve looked to other scripts, i’ve seen grep used faulty that involves piping the output of cat to grep for searching the contents of a single file. This is waste of time(computer cycles), because grep take file names as arguments.
