Yearly Archives: 2014


Bash script: How to check if it run by a user in terminal or not 2

We will use ‘tty’ which normally prints the file name of the connected terminal on standard input.

To make our life easier we will add the parameter -s (silent), ‘tty -s’  will print nothing and return an exit status.

tty has the following possible values for exit status:

  •  0: if standard input is a terminal
  • 1: if standard input is not a terminal
  • 2: if given incorrect arguments
  • 3: if a write error occurs

So in order to check if this script is attached to a terminal we have to do something similar to this:
tty -s;
if [ "0" == "$?" ]; then
echo "Terminal attached, you can print data as there might be a user viewing it.";
else
echo "No terminal attached, there might not be a reason to print everything.";
fi

Note: In the above script we use ‘$?’, that variable contains the return value of the last executed command, so If you are planning on using it like this, make sure you do not place any other command in between the tty -s and the if statement.


How to: remove prefix and suffix from a variable in bash 3

string="/scripts/log/mount_hello_kitty.log";
prefix="/scripts/log/mount_";
string=${string#$prefix}; #Remove prefix
suffix=".log";
string=${string%$suffix}; #Remove suffix
echo $string; #Prints "hello_kitty"

In the above example we have as input the variable string that contains following /scripts/log/mount_hello_kitty.log.

We want to remove from that variable the prefix, which is /scripts/log/mount_ and the suffix, which is .log.

The above code will replace in place the input that is contained in the variable string and remove the prefix and suffix we defined in the respective variables.

string=${string#$prefix} returns a copy of string after the prefix was removed from the beginning of the variable.

string=${string%$suffix} returns a copy of string after the suffix was removed from the end of the variable.


How to: Extract all usernames that are logged in from who

who | cut -d ' ' -f 1 | sort -u

who: will show who is logged on

cut  -d ‘ ‘ -f 1: will remove all sections from each line except for column 1. It will use the space character as the delimiter for the columns

sort -u: it will sort the usernames and remove duplicate lines. So if a user is logged in multiple times you will get that username only once.
In case you want to filter out root user from this list you can do it as follows:

who | cut -d ' ' -f 1 | sort -u | grep -v 'root'


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