Monthly Archives: October 2014


Generate Random Password

date +%s | sha256sum | base64 | head -c 32 ; echo
date +%s : will print the system date and time in seconds since 1970-01-01 00:00:00 UTC

sha256sum :  will compute  the SHA256 message digest of the time in seconds we produced before

base64 : will encode the previous data and print them to standard output

head -c 32 : will print the first 32 characters of the previous data

; echo : is used to create a new line at the end of the results


Bash: Close a range of open sockets by killing the PIDs that are holding them open

Sometimes you want to use a specific port number but some other process(es) is using it. To get the control of the port you need to terminate all other processes and free it.
To find out which process(es) you need to kill, use lsof -i :port. It will return a list of each command and PID that is using the specific port. After that kill those PID using kill -s 9.

The following script will accept a range of ports to free, and for each it will try to kill all processes that are holding them blocked.

low=12345;
high=12350;
for i in `seq $low $high`; do
  lsof -i :$i | tail -n +2 | awk '{system("kill -s 9 " $2)}';
done

Using tail -n +2 we skip the first line of the input which would be the header information.
The system method will invoke a new sh shell and execute the command in it.
Using kill -s 9 we signal the processes that they have to terminate immediately.


Bash: Get Filename, File Extension and Path from Full Path

The following commands will allow you extract various information from the full path of a file.

Part of the information is the filename, the file extension, the file base and the directory it is located in.

# Truncate the longest match of */ from the beginning of the string
filename="${fullpath##*/}";
# Get the sub-string from the start (position 0) to the position where the filename starts
directory="${fullpath:0:${#fullpath} - ${#filename}}";
# Strip shortest match of . plus at least one non-dot char from end of the filename
base="${filename%.[^.]*}";
# Get the sub-string from length of base to end of filename
extension="${filename:${#base} + 1}";
# If we have an extension and no base, it means we do not really have an extension but only a base
if [[ -z "$base" && -n "$extension" ]]; then
  base=".$extension";
  extension="";
fi
echo -e "Original:\t'$fullpath':\n\tdirectory:\t'$directory'\n\tfilename:\t'$filename'\n\tbase name:\t'$base'\n\textension:\t'$extension'"