Looking to optimize code

Hi guys,

I feel a bit comfortable now doing bash scripting but I am worried that the way I do it is not optimized and I can do much better as to how I code.

e.g.

I have a whole line in a file from which I want to extract some values.

Right now what I am doing is :

STATE=`cat /opt/scripts/start.log | awk '{print $3}'`
TIME=`cat /opt/scripts/start.log | awk '{print $2}' | cut -d, -f1 `
DATE=`cat /opt/scripts/start.log | awk '{print $1}'`

echo " The app started at $STATE $TIME with state $STATE."

Is this a good way to extract 3 words (strings) from a line of text ? Or is there a better/more optimized way of doing this ?

At least you can avoid the execution of cat; awk can directly read the file.
It is a bit strange that your file seems to be a log file - what happens if it has more than one line?
The following efficient shell builtin reads one line into three variables

read DATE TIME STATE  < /opt/scripts/start.log

Might need some little post processing...

And the post processing MadeInGermany mentioned would be something like:

TIME=${TIME%%,*}

followed by the echo you already had.

And that post processing that Don used is an example of what you can do with Parameter Substitution. There are many other ways you can carve a piece of information out of a string, without the need of invoking an external program, which it will always be slower that using the built-in shell functionalities.

Finally: you won't need the subshell execution any more utilizing the advice you already got, but for future reference, in the cases where you do need it: the backticks should not be used any more! They are a leftover from the original Bourne shell, which is outdated by some 25 years now. Use the modern POSIX way of process substitution:

variable=`command1 | command2`     # old, do not use!
variable=$(command1 | command2)    # the modern way to do the same

I hope this helps.

bakunin

And, as there may be more than those three strings in a line, you might want to provide for a "sag wagon" for the trailing rest:

read DATE TIME STATE REST < /opt/scripts/start.log
1 Like