GNU/Linux


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


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##*.}`