Friday, January 2, 2015

count number of files by type

A basic solution for counting types of files in a directory.

find -type f -name "*.js"|grep -c .js

Taking apart the one-liner , find executes by defining we are looking for a regular file (-type f) and the name ends with js (-name "*.js"). Then we pipe it to grep to suppress the grep output and prints the number of lines coming from the pipe(-c) and matching the .js string.

Wednesday, November 26, 2014

acting on command output

you can catch/parse the output of a command and act upon it.

a basic example below is for mysql service status.

[[ $( { mysql status >/dev/null; } |& grep "Can't connect" | wc -l ) -eq "1" ]] && service mysql start



it's basically a one liner condition. the first part before the && should return non-false for the second part to execute. if service is not recognised

when we try

echo $( { mysql status >/dev/null; } |& grep "denied" | wc -l )

>1


if you have a mysql server running, it will need a user/password to run the mysql command. And since we don't supply it, you will get the standart

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

and within that response there's our denied keyword, that we are checking with grep. That output is piped to wc which prints the new line count, and that would be 1 if the server is down. So the equals to 1 is true and the start command is executed. You can call the mysql script under /etc/init.d or /etc/rc.d/init.d instead of service . This kind of execution is good for maintenance and conditional executions.