All posts by Naveen Tamanam

How to edit or change commit history using git rebase

Do you ever wonder about rewriting git commit history. Here is how you can do. One great advantage we get with git version control system is that, we can edit or rewrite the history of commits. Some times may be you want to publish the different commit history or for some reason you may want to edit the few chunks for commit history.

There are different ways to edit the history of commits. There is one quick way to edit the very last commit or HEAD. Using following command

git commit --amend

If you want to edit selected commits in the history, you can do it using feature called rebasing in git. Rebasing is a great feature in git. Other than process called merging  we can use rebasing to merge different branches in different way other than usual git merge. One of the advantage is we can rewrite the history to make sure commit history looks like the way you want.

We have to use interactive rebasing to edit the commit history, using the following command

git rebase -i   <commit>

where we specify the commit  which is parent of the commit  from which you want to edit the commit history

Lets say I chosen the commit from where I want to edit the history, I would type the following command

git rebase -i 185a4d16eb696e37a061bc9547b219b5d147cdff

If you perform above command, you wold see the following content in the default editor,

pick 28efa32 Added feature request #f12
pick 38ffdf3 Fixed bug #228 
pick f7f3f6d Fixed typeos
pick 310154e updated REDEME and INSTALL
pick a5f4a0d added cat-file

# Rebase 710f0f8..a5f4a0d onto 710f0f8
#
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

The above content is self explanatory, if you want to remove commits just remove corresponding commit line. if you want to abort interactive rebase any time use git rebase –abort. You should notice that your last commit is at bottom. These commits from chronological from top to bottom.

If you chose to edit the selected commits, let’s say want to change author, you have to replace the word pick with word edit for that corresponding commits and quit the editor by saving. Then you will stop at the first commit, you can change the author using following command

git commit --amend --author "user name <user@email.com>"

Like wise you can change the commit message as well. Of course you can also change the content of files to commit

and then to continue rewriting history using following command,

git rebase --continue

You have to  repeat these steps for each commit that you change the  word pick to edit. Git will stop to let you amend the commit. Once you are finished with specific commit, you can proceed further by using rebase command using command line argument –continue. 

Once you finished with rebase, you may see the following message

Successfully rebased and updated refs/heads/unstable.

If you get conflicts, you have to resolve them in the way you resolve for merging process. Once you resolved the conflicts by removing conflict markers(>>>>>> ======= <<<<<<<). Use to git add  to mark them resolved. Then continue to rebase using command

git rebase --continue

 

WARNING:

Beware of rebase,  you may corrupt the commit history  of your team members and it may leads to confusion.

If you are learning don’t try to experiment it on real repository. Instead you create the dummy repo and get hands on experience.

You may produce merge conflicts sometimes, you may have to resolve to proceed the rebase

Want to read more?

References:

[1] https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History

[2] https://git-scm.com/book/en/v2/Git-Branching-Rebasing

 

How to truncate empty lines using sed

Sed command is very helpful  for text processing. It’s just matter of regular expression. Here is how you can  truncate empty lines  in the file using command sed.

$ sed   '/^\s*$/d' <file_name>

The above command will give you the output by deleting empty lines. If you want to modify the original file itself. You use the option -i

$ sed  -i '/^\s*$/d' <file_name>

Example:

I have a file with following data and named as numbers

$ cat numbers
2989239823
8239823922

3892389239
2938923829
923892389

838888888



000000000

Now see, the way to truncate empty lines using sed

$ sed '/^\s*$/d' numbers 
2989239823
8239823922
3892389239
2938923829
923892389
838888888
0000000000

The above command won’t change the original file. If you want to change original use option -i

sed -i '/^\s*$/d' numbers 

Explanation:

Sed interprets ‘/^s*$/d’  and giving us the desired output. Here  text between slashes(/regular expression/) represent the regular expression followed by sed command “d”  means delete.  So command sed matches the lines with given regular expression. If it finds the match it applies the command.

 

How to change hostname of the linux machine

Host name is the name or label which is assigned to your computer that is used to identify and communicate. Usually you can choose your hostname while installation of operating system. If you take a server you may get machine with pre labeled hostname. It is always possible to change the hostname.

Note: You need root or sudo access to change the hostname of the machine.

There are different ways to changes the hostname of the computer. you  canchoose one of them. There is a volatile way and not volatile way. If you want change host name of the computer permanently you need to write your hostname in couple of files. If you want to change instantly (temporarily) you can change using couple of commands, but this change is volatile you will loose your hostname after reboot.

Using command hostname

Now, we will see  the way to change hostname instantly. This is not a persistent change. You will loose after reboot

The command hostname without arguments will display the current hostname of the system

$ hostname 
lintel.in
$ sudo hostname lintel.in

Where you can give qualified hostname in the place of lintel.in. If you are using desktop linux(ubuntu) you can observer your change on (new session)shell, ie, user@hostname

Using sysctl

sysctl is the command that we use to configure kernel parameter at runtime. We can change hostname using this command as well. You can query the hostname using sysctl  as

$ sysctl -a | grep hostname

To change hostname,

$ sudo sysctl kernel.hostname=example.com

Changes made using either way are volatile. To make permanent change. Follow the below steps.

Edit hostname file

You have to edit the file /etc/hostname to make persistent change. This file contains only the hostname. To update hostname,

$ sudo echo newhostname > /etc/hostname

Including the above change you may need to edit /etc/hosts file. Change the 127.0.0.1   old_hostname  section. Replace old hostname with new hostname if you find.

it could be something like

127.0.0.1  lintel.in

Restart the machine to get your changes applied. You can combine both ways to get new hostname now and then after reboot.

Using hostnamectl

The linux distributions are also providing the command called hostnamectl to manage and set the hostname.

hostamectl with out any arguments will give the system hostname and other misc details

Check hostname

hostnamectl status

Set the hostname using hostnamectl

hostnamectl set-hostname "Stephen's notebook"

Chaging hostname using nmcli

Oh yeah, you can change the hostname using command nmcli as well. This command can be used to set the static hostname.

Query the hostname

nmcli general hostname

Change the hostname

nmcli general hostname lintel.in

 

How to listen on an arbitrary port and print the data which is coming using netcat

We are well known about  telnet which is pretty much handy tool to debug and open a TCP connection to remote server:port. But we want the tool which will listen on given port for connections unlike telnet. Yeah, there is tool called netcat. Usually it comes with many linux distributions by default, also called nc. There is also a windows version . According to the scope of the article we will see how to open a TCP or UDP connection and print the data sent by connected clients, but this tool  is more than capable of just listening on port for a connection.

Synopsis

nc [-46DdhklnrStUuvzC] [-i interval] [-p source_port] [-s source_ip_address] [-T ToS] [-wtimeout] [-X proxy_protocol] [ -x proxy_address[ :port]] [hostname] [port[s]]

 

Listen for UDP on specific host and port using netcat

Listen for the connections and print the data sent by the clients

nc -lvu [IP Address] 5060

nc -lvu  5060
nc -lvu  192.168.0.5 5060

nc is the command alias for netcat.

The break down of above command

l        Forcing netcat to listen on given host and port instead of opening/making  connection with remote host and port

v          Give verbose output

u          Use UDP. That is, listen for UDP on give port, by default it listens for TCP unless we give this option.

Ip Address   It is optional, if it is not specified localhost will be used

Port                You must specify the port on which nc should listen on.

Listen for TCP on specific host and port using netcat

nc -lv 9876

This is same as UDP mentioned above except we haven’t specified the option -u . Where netcat will listen on TCP port by default with out that option.

Now netcat is listening on the given port on localhost. You can connect to this TCP port from the other  tab(terminal)   using either netcat or telnet

Connect Using Telnet
telnet localhost  9876
Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

Hello

After  connected, type “Hello”, you should see that text in the tab where netcat is listening

Connect Using NetCat
nc localhost 9876
$ nc localhost 9876
Hello
Connected, sending text

After   connected,  we sent some text. It should be displayed on tab where nc is listening.

You can quit the client by sending interrupt  CTRL + D. If you quit the client, the server(nc command) will also stop listening. We can use the option -k     to forces nc to stay listening for another connection after its current connection is completed.  It is an error to use this option without the -l option.

nc -lkv 9876

I hope, these examples gave you some good understanding. As you can see, we can use nc as both server and client. Practically it is more capable than you think. If you are networking geek or dealing with network application or protocols. You can find this handy for your debugging purpose.

Case Studies

Let’s say, I have web hook URL configured on other 3rd party website. I want to check whether that server is sending events or not. If sending, I would like to see how is API and message format and I don’t have my program ready yet. In such a case, you simply listen on host and port which are configured on 3rd party web site to receive events and simply you can check the data received by nc 

Something like,

$ nc -lvk 8080
GET /user_login HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Upgrade-Insecure-Requests: 1

The tool netcat (nc) is very powerful tool, it is very simple tool but there are lot of possibilities. Anti-viruses on windows will detect this program as malware sometimes. Where it can also be used as a backdoor.

How to find width and height of the terminal in linux

You may wonder how do I find the number of characters will fit in a line in the terminal or size of the window. There are several ways to figure out the size of the window. Let’s go through the different ways to find size of terminal

First lets see different ways that you can use to figure out width and height of terminal in terms of characters

  1. Using command tput
  2. Using command stty
  3. Using environment variables

    Using command tput

The command tput is very helpful to query the terminal information and to do some other simple operations like placing cursor at required random position.

Here is how you can find the width and height of terminal. You may call it as number of rows and columns

$ tput lines
36
$ tput cols
141
$ echo "columns: `tput cols` Rows: `tput lines` "
columns: 141 Rows: 36 

Using command stty

This is also one of the command which useful to query,change and print terminal line settings.

The simple output of stty command regarding information of terminal

stty
speed 38400 baud; line = 0;
eol = M-^?; eol2 = M-^?; swtch = M-^?;
ixany iutf8

Command to get lines and columns count in characters

$ stty size
39 143

🙂

Using environment variables

On you terminal always you can query the size of the terminal using the environment variables $COLUMNS

$ echo "$LINES $COLUMNS"
39 143
$ echo "$LINES $COLUMNS"   # Resized the window
22 79

Values of those environment variables will change if size of the terminal window changes.

How to check certificate information of web server using openssl

In this article we will see how to check certificate information of webserver using command line tool openssl

The below command will get you the valid period of the ssl certificate.

naveen@lintel:~$ echo | openssl s_client -connect www.google.com:443 2>/dev/null | openssl x509 -noout -dates
notBefore=Dec 10 18:03:47 2015 GMT
notAfter=Mar  9 00:00:00 2016 GMT

To check the certificate information of web server, use the following command. Here I’m using google.com in this example

naveen@lintel:~$ echo | openssl s_client -connect  google.com:443 -showcerts

Export certificate into a file

naveen@lintel:~$ openssl s_client -connect  www.google.com:443 -showcerts < /dev/null  | openssl x509 -inform PEM  -text -out cert

If you want to extract the public key from the certificate, here is how you can do

naveen@lintel:~$ openssl s_client -connect  www.google.com:443 -showcerts < /dev/null  | openssl x509 -inform PEM  -pubkey
depth=2 C = US, O = GeoTrust Inc., CN = GeoTrust Global CA
verify error:num=20:unable to get local issuer certificate
verify return:0
DONE
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlcHKTjv57a9GHLxMDCCO
qW+qCh9JGYxX0QlBCTOz71oNPKlC8HzfGfx3nl0EXnOGJqUMbdLtke1+6lTKwJ8z
kArVrGvedfkpc7kV2i2g3AtD/7E+ig9sZ8hU1Rffzqt5OOMGqUKKDmC0JXh67uhY
t1GCTNsS6vIyl0qLWjoWBI2P+v7zL2VUFWnM3zLLvBWTy9tqmoFcGxHGtpmgvA0/
aBI1ZaYoojEVOEJ80jbg/67LJJalF7kbPjA0D45K4dFc82IDqIx768bbRTxxVK5j
BlVpCoj4MCCt3/HyOgKNlOB1ChHOfm54ELm4OWJC3ZMQUjzUnAX33/SLKQrv1dLe
KwIDAQAB
-----END PUBLIC KEY-----
-----BEGIN CERTIFICATE-----
MIIEgDCCA2igAwIBAgIITq9JKLrGf5EwDQYJKoZIhvcNAQELBQAwSTELMAkGA1UE
BhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMxJTAjBgNVBAMTHEdvb2dsZSBJbnRl
cm5ldCBBdXRob3JpdHkgRzIwHhcNMTUxMjEwMTgwMzQ3WhcNMTYwMzA5MDAwMDAw
WjBoMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwN
TW91bnRhaW4gVmlldzETMBEGA1UECgwKR29vZ2xlIEluYzEXMBUGA1UEAwwOd3d3
Lmdvb2dsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCVwcpO
O/ntr0YcvEwMII6pb6oKH0kZjFfRCUEJM7PvWg08qULwfN8Z/HeeXQRec4YmpQxt
0u2R7X7qVMrAnzOQCtWsa951+SlzuRXaLaDcC0P/sT6KD2xnyFTVF9/Oq3k44wap
QooOYLQleHru6Fi3UYJM2xLq8jKXSotaOhYEjY/6/vMvZVQVaczfMsu8FZPL22qa
gVwbEca2maC8DT9oEjVlpiiiMRU4QnzSNuD/rssklqUXuRs+MDQPjkrh0VzzYgOo
jHvrxttFPHFUrmMGVWkKiPgwIK3f8fI6Ao2U4HUKEc5+bngQubg5YkLdkxBSPNSc
Bfff9IspCu/V0t4rAgMBAAGjggFLMIIBRzAdBgNVHSUEFjAUBggrBgEFBQcDAQYI
KwYBBQUHAwIwGQYDVR0RBBIwEIIOd3d3Lmdvb2dsZS5jb20waAYIKwYBBQUHAQEE
XDBaMCsGCCsGAQUFBzAChh9odHRwOi8vcGtpLmdvb2dsZS5jb20vR0lBRzIuY3J0
MCsGCCsGAQUFBzABhh9odHRwOi8vY2xpZW50czEuZ29vZ2xlLmNvbS9vY3NwMB0G
A1UdDgQWBBTRV+KjkFiVN5eQP1h1Fz4F4rTwbzAMBgNVHRMBAf8EAjAAMB8GA1Ud
IwQYMBaAFErdBhYbvPZotXb1gba7Yhq6WoEvMCEGA1UdIAQaMBgwDAYKKwYBBAHW
eQIFATAIBgZngQwBAgIwMAYDVR0fBCkwJzAloCOgIYYfaHR0cDovL3BraS5nb29n
bGUuY29tL0dJQUcyLmNybDANBgkqhkiG9w0BAQsFAAOCAQEAQr4lzcjyBQZ5fn/Z
drUDqpN4fx8Sa6hafoGVOfWMktt003x8ylXb3Pxhgw27f6wiFFRXlX85a2F0/AnC
eoV23mHmV6/0mOwocVYt/Th96WNGGmhANkFW//HCphRWnhaOqIG6yFRQ/jxArTvZ
QJEGI5AiYHzQn7LdUM8mH1o3ifR+lX+QiAwyeU9oegdlRslI2KMoPOuOFj329NFx
Bw+XVQXMsRJITPg8pnegPmLCOjpz8y7pBxbxGnfaI66I8X4dArsaXX4r5mkfhk2e
mm7fxQ8qUaW9mKoW0XvwGxU0AwKI8OopuXHoD97vr2GSK0QNZ19A96mtTWnQ2cu2
i9qjGw==
-----END CERTIFICATE-----

 

References:
[1] Certificates and Encodings

 

How to check, add and delete routes in linux

There are two commands which are useful either to add or delete route, those are  route and ip. We will see how to change route using command route.

Route Synopsis

route
[-v] [-A family] add [-net|-host] target [netmask Nm] [gw Gw] [metric N] [mss M] [window W] [irtt I] [reject] [mod] [dyn] [reinstate] [[dev] If]
route
[-v] [-A family] del [-net|-host] target [gw Gw] [netmask Nm] [metric N] [[dev] If]
route
[-V] [--version] [-h] [--help]

To check the routing table

Command: nestat -rn

$ netstat -rn
Kernel IP routing table
Destination  Gateway      Genmask        Flags MSS Window irtt Iface
0.0.0.0      192.168.0.1  0.0.0.0        UG    0   0      0    wlan0
192.168.0.0  0.0.0.0      255.255.255.0  U     0   0      0    wlan0

Adding route

sudo route add -net 192.168.3.0 gw 192.168.1.1 netmask 255.255.255.0 dev eth0

Deleting route

sudo route del -net 192.168.3.0 gw 192.168.1.1 netmask 255.255.255.0 dev eth0

A quick way to add default route

route add default gw 192.168.1.1

A  quick way to delete defualt route

route del default gw 192.168.1.1
MySQL Tips

MySQL tips for beginners and intermediate

This article will take you through few MySQL tips those are pretty helpful.

We will start with few useful statements,

Do you know, if you are working offline with mysql  and you need some help on syntax. You can get it right away on terminal  with simple statement  help followed by command or statement.

help

mysql> help  <COMMAND or STATEMENT>

The above statement in the mysql console will give you the whole syntax and it’s usage.

Here is  an example:

mysql> help create database
Name: 'CREATE DATABASE'
Description:
Syntax:
CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
    [create_specification] ...

create_specification:
    [DEFAULT] CHARACTER SET [=] charset_name
  | [DEFAULT] COLLATE [=] collation_name

CREATE DATABASE creates a database with the given name. To use this
statement, you need the CREATE privilege for the database. CREATE
SCHEMA is a synonym for CREATE DATABASE.

URL: http://dev.mysql.com/doc/refman/5.6/en/create-database.html


For suppose you want know available list of date and time functions. Here is how you will get,

mysql> help  date and time functions;
You asked for help about help category: "Date and Time Functions"
For more information, type 'help <item>', where <item> is one of the following
topics:
   ADDDATE
   ADDTIME
   CONVERT_TZ
   CURDATE
   CURRENT_DATE
   CURRENT_TIME
   CURRENT_TIMESTAMP
   CURTIME
   DATE FUNCTION
   DATEDIFF
   DATE_ADD
   DATE_FORMAT
   DATE_SUB
   DAY
   DAYNAME
   DAYOFMONTH
   DAYOFWEEK
   DAYOFYEAR
   EXTRACT
   FROM_DAYS
   FROM_UNIXTIME
   GET_FORMAT
   HOUR
   LAST_DAY
   LOCALTIME
   LOCALTIMESTAMP
   MAKEDATE
   MAKETIME
   MICROSECOND
   MINUTE
   MONTH
   MONTHNAME
   NOW
   PERIOD_ADD
   PERIOD_DIFF
   QUARTER
   SECOND
   SEC_TO_TIME
   STR_TO_DATE
   SUBDATE
   SUBTIME
   SYSDATE
   TIME FUNCTION
   TIMEDIFF
   TIMESTAMP FUNCTION
   TIMESTAMPADD
   TIMESTAMPDIFF
   TIME_FORMAT
   TIME_TO_SEC
   TO_DAYS
   TO_SECONDS
   UNIX_TIMESTAMP
   UTC_DATE
   UTC_TIME
   UTC_TIMESTAMP
   WEEK
   WEEKDAY
   WEEKOFYEAR
   YEAR
   YEARWEEK

 

status

The  status statement in the mysql console will give you the quick overview about connection, mysql server and client details

mysql> status
--------------
mysql  Ver 14.14 Distrib 5.6.27, for debian-linux-gnu (x86_64) using  EditLine wrapper

Connection id:		38
Current database:	
Current user:		root@localhost
SSL:			Not in use
Current pager:		stdout
Using outfile:		''
Using delimiter:	;
Server version:		5.6.27-0ubuntu0.14.04.1 (Ubuntu)
Protocol version:	10
Connection:		Localhost via UNIX socket
Server characterset:	latin1
Db     characterset:	latin1
Client characterset:	utf8
Conn.  characterset:	utf8
UNIX socket:		/var/run/mysqld/mysqld.sock
Uptime:			6 hours 4 min 6 sec

Threads: 1  Questions: 112  Slow queries: 0  Opens: 87  Flush tables: 1  Open tables: 80  Queries per second avg: 0.005

Pager

Are you frustrated with querying lot of records to analyze in mysql conventional command line client console? No worries,  can set the pager in mysql client console. You can set it to either less or more. Here is the way to do it,

mysql>\P less
PAGER set to 'less'
mysql>\P more
PAGER set to 'more'

Let’s say if you set pager to less, you will see your query output like wise when you read file using less command. You try the following statements.

mysql>\P less
mysql>show status;
Reset pager:

you can reset your pager using \P with arguments;

mysql>\P

Processlist

The following statement show processlist will give you overview about all connected clients and their work, even queries they are being executed,

mysql> show processlist;
+----+------+-----------+------+---------+------+-------+------------------+
| Id | User | Host      | db   | Command | Time | State | Info             |
+----+------+-----------+------+---------+------+-------+------------------+
| 38 | root | localhost | NULL | Query   |    0 | init  | show processlist |
+----+------+-----------+------+---------+------+-------+------------------+
1 row in set (0.00 sec)

explain

An other statement which very helpful in optimizing your queries and schema is explain . You can’t imagine how helpful this statement is, it will show how mysql is using indexes how many rows or records it’s searching for a result. Based on the report you can optimize the queries and even you can add indexes to table if required to speed up results.

Here is simple example,

mysql> EXPLAIN SELECT t.term_id, tt.parent, tt.count, tt.taxonomy FROM wp_terms AS t INNER JOIN wp_term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy IN ('category') ORDER BY t.name ASC;
+----+-------------+-------+--------+---------------------------+------------------+---------+---------------------------+------+-----------------------+
| id | select_type | table | type   | possible_keys             | key              | key_len | ref                       | rows | Extra                 |
+----+-------------+-------+--------+---------------------------+------------------+---------+---------------------------+------+-----------------------+
|  1 | SIMPLE      | t     | ALL    | PRIMARY                   | NULL             | NULL    | NULL                      |    1 | Using filesort        |
|  1 | SIMPLE      | tt    | eq_ref | term_id_taxonomy,taxonomy | term_id_taxonomy | 138     | wordpress.t.term_id,const |    1 | Using index condition |
+----+-------------+-------+--------+---------------------------+------------------+---------+---------------------------+------+-----------------------+
2 rows in set (0.00 sec)

You will see a record for each table from which you are selecting or used in query. Find more about explain here

 

Other than few handy statements explained above, now we will go through few tips to avoid common pit falls in MySQL.

  • Always try to avoid creating the user with wildcard host . Doing so will mitigate the possible risks of getting hacked.
  • Only give required permissions to the user, so other databases or things will not get screwed up either intentionally or accidentally because of user or script.
  • When you are deleting something from production or from important place, use transactions. Here is how you will do it,
mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> -- do you work like deleting records and other stuff
mysql> delete from users where id in (1, 3, 4);
mysql>commit;

This is useful to avoid common problems caused by either typos or accidental mistakes. Before you type commit, you can always review your changes and rollback if changes are unintended.

ysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> -- do you work like deleting records and other stuff
mysql> delete from users;  -- lets say you forgot where  in delete query
mysql>rollback;   -- You can rollback your accidental mistake

A quick guide to install SIP monitoring tool sngrep

A simple quick quide to install SIP monitoring tool sngrep in seconds

To install sngrep download the source from github. Clone it

$ git clone https://github.com/irontec/sngrep.git

Go to cloned repo and configure it

./bootstrap.sh
./configure

Compile

$ make

You can run sngrep after you compile it (assuming you are in repo)

$ src/sngrep

But to use it as installed command, you have to install it

$ sudo make install

Once you installation is finished you can monitor the SIP traffic and see the live call flow by simply running the command

$ sngrep

 

How to delete empty files and directories recursively

We can use  find command to delete all empty files and directories recursively

To delete empty files

$ find ./path -type f -empty -delete

To delete only empty directories

$ find /path -type d -empty -delete

If you omit filter -type, it will delete both directories and files.

You can control the how deep the find  command can go and delete the empty directories and files.

Let’s say I have this directory tree

Directory Tree
Directory Tree

As you can see, we have 3 levels of directories (and files). All are empty, this is to give you better illustration.

To control how deep we search to delete empty files and directories and from which level we should delete. We would use the following two options

-maxdepth levels
Descend at most levels (a non-negative integer) levels of directories below the command line arguments. -maxdepth 0
means only apply the tests and actions to the command line arguments.

-mindepth levels
Do not apply any tests or actions at levels less than levels (a non-negative integer). -mindepth 1 means process all files
except the command line arguments.

These options (-maxdepth and -mindepth) should be provided immediately after the last path.

The simple find command below will print all files till level 3

$ find a -maxdepth 3
a
a/filea.txt
a/b
a/b/c
a/b/c/filec.txt
a/b/fileb.txt

Let’s say if you want to delete only the deepest or very last directory and files which are empty. You can do so,

find a -maxdepth 3 -mindepth 2
a/b/c
a/b/c/filec.txt
a/b/fileb.txt

You can delete them by adding -delete action to above command

find a -maxdepth 3 -mindepth 2 -empty -delete

Apparently only a/b/c/filec.txt and a/b/fileb.txt will be delete because the director c is not empty.

The command find is great utility that every linux geek should know.