bash


Linux Bash: How to print leading zeroes on a variable

In order to print the leading zeros to a variable you need to use the function printf as follows, where %03d states that the number should consist of minimum 3 digits and thus it will put the missing leading zeros:

 printf %03d $counter

The following example renames a file that it has the following format for a filename: number.anything and adds the leading zeros in order to make it easier while sorting multiple files.
The name is contained in the variable $a.
If for example we had the file 11.txt  it will become 0011.txt

mv $a `printf %04d.%s ${a%.*} ${a##*.}`

 


Linux Bash: How to find a string inside C/C++ Source and Header Files

Just issue the following in the folder of the source codes and replace ‘FIND ME’ with the string you want to query:

find -O3 . -regex '.*\.\(c\|cpp\|h\)

You can change the contents of the regular expression to search in different file extensions (file types).  -exec grep 'FIND ME!' -sl '{}' \;

You can change the contents of the regular expression to search in different file extensions (file types). 


Ubuntu Linux: How to register machine IPs and domain name to web-server using php

First of all you will need a page the will keep record of the registrations.

To do the paste the following code in a *.php file on a php-enabled webserver:

<html>
<body>

<?php
if (isset($_GET["ip"]) && isset($_GET["name"]))
{
  echo "Current Time " . gmdate("d/m/Y H:i:s e", $_SERVER['REQUEST_TIME']) . " IP " . $_GET["ip"] . " Hostname " . $_GET["name"] . "!<br/>"; 
  $file=fopen("cookies.txt","a") or $file=fopen("log.txt","x");
  fwrite($file,"Time " . gmdate("d/m/Y H:i:s e", $_SERVER['REQUEST_TIME']) . " IP " . $_GET["ip"] . " Hostname " . $_GET["name"] . "\n" );
  fclose($file);
}
else
{
  echo "Welcome Murloc!<br />";
  echo "Following the SSH Login Log File:<br /><br />";
  $file=fopen("log.txt","r") or $file=fopen("cookies.txt","x");
  while(!feof($file))
  {
    echo fgets($file). "<br />";
  }
  fclose($file);
  echo "Your IP is ".$_SERVER['REMOTE_ADDR']. "<br />Current Time " . gmdate("d/m/Y H:i:s e", $_SERVER['REQUEST_TIME']) . "<br /><br />";
  echo "Bye Bye Bob<br />";
}
?>
</body>
</html>

The above php script will store your IP and Hostname if you provide them on the URL along with the time that the event happened and if you do not then it will list the registered IPs.

NOTE:Not sure how safe this code is

In order to invoke it / send you IP and hostname, issue form bash the following:

IPs=`ifconfig  | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'`
wget "http://www.example.com/ip.php?ip=$IPs&name=$HOSTNAME" -o /dev/null