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
do 
      echo $i
done


Alternative:

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

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.

Python:
 //1.py
#!/usr/bin/env python
print("hellow")

#get aruguments using argv array
# more python commands

Run: ./1.py




Scala:
//1.scala
#!/usr/bin/env scala
println("hellow")


Run: ./1.scala

or 

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


This one is interesting!

It can be executed as normal script

sh  1.sh 
or 
./1.sh

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.

#!/bin/bash
START_TIME=`date +%s`
# Run commands
# Run commands
END_TIME=`date +%s`
EXECUTION_TIME=`expr $END_TIME-$START_TIME`
 
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.

$COMMAND [ARGUMENTS]

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 $#.



FORCE PUSH TO REMOTE 

Forcefully push your local contents to the remote repository:
(Caution: the remote repository files could be replaced by the local files)

git push --force-with-lease





No comments:

Post a Comment