Skip to content

bash

How to put apart "call" and source in bash

1
(return 0 >& /dev/null) && echo sourced || echo called

Good error handler for bash

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
on_err() {
        local rc=$? line file
        read -r line file < <(caller)
        echo "ERROR:$rc:$file:$line:${BASH_COMMAND@Q}"
        local -i i=0
        while caller $i | while read -r line func file; do printf '%2d: %-15s %s:%d\n' "$i" "$func" "$file" "$line"; done; do
                ((i+=1))
        done
        exit $rc
}>&2
trap on_err ERR
set -eE -o pipefail
Output may look like
1
2
3
4
5
ERROR:1:./xx.sh:15:'false'
 0: func            ./xx.sh:15
 1: func2           ./xx.sh:19
 2: func3           yy.sh:5
 3: main            yy.sh:8

Pure bash whois client

1
2
3
QUERY=as21416
WHOIS=whois.ripe.net
(exec 5<>/dev/tcp/$WHOIS/43; echo $QUERY>&5; while read -ru5; do echo "$REPLY"; done)

Remove leading zeroes ${VAR##+(0)}

1
2
3
4
5
6
7
8
jno:~$ shopt extglob
extglob         on
jno:~$ a='000000123'
jno:~$ declare -p a
declare -- a="000000123"
jno:~$ shopt -q extglob && echo ${a##+(0)} || { echo $a | sed -e 's/^0\+//'; }
123
jno:~$

Found here.

URLencode for Shell using jq

stackoverflow

1
2
3
4
5
$ printf %s 'input text'|jq -sRr @uri
input%20text

$ jq -rn --arg x 'input text' '$x|@uri'
input%20text

Who has eaten all the swap?

1
2
3
4
5
6
7
8
for file in /proc/*/status ; do
    awk '
        /VmSwap|Name/   { printf $2 " " $3 }
        END     { print "" }
    ' $file
done |
sort -k 2 -n -r |
less

When the password was changed?

  1. chage -l $USER — show password "aging" status
  2. passwd -S $USER — show user's "status"
  3. zgrep -Fw passwd /var/log/* /var/log/*/* | grep -Fw $USER — look for passwd(1) report