Friday, April 17, 2015

Cool Shell Utilities

In this page, I will try to include the cool bash shell utilities that will help us a lot.

Task 1. Search all files in sub directories in iterative way

find . -type f -name '*.mp3'  | while read i
      echo $i


for file in 'find . -iname "*.mp3" 
    echo $file

Task 2. Create python/scala directly runnable from script

For Linux system, bash is very powerful. We can do almost anything using shell scripts. And Ubuntu comes with python already installed. So, to write python scripts is very straightforward. And if you have already installed JVM, then a more powerful and faster programming language "Scala" makes it even better to write scripts.  So, basically, I wanted to write, a python or scala program and run from a shell script.

#!/usr/bin/env python

#get aruguments using argv array
# more python commands

Run: ./

#!/usr/bin/env scala

Run: ./1.scala


exec scala $0 $@
// Say hello to the first argument
println("Hello, " + args(0) + "!")

This one is interesting!

It can be executed as normal script


File extensions do not matter after we define environment

Task 3:  Get run time of the script

If we need to calculate how much time it takes to get an script executed, we can do that using date  command as follows.

START_TIME=`date +%s`
# Run commands
# Run commands
END_TIME=`date +%s`
Task 4: Pass parameters to bash script

We frequently need to send command arguments to the bash script and this is quite easily implemented in bash script. We execute the command with parameters.


In command itself, we should receive the parameters and the parameters are automatically stored in the variables such as
$1, $2

That means, if we send two parameters, these parameters are stored in variables $1,$2.

We can get the number of parameters using the variable $#.