Threads in bash 2

you want threads in bash and know exactly when they finish and in which state?

#!/bin/bash

threads=()
f_getThreadKeyword(){ for i in ${threads[@]}; do [[ $(echo $i|cut -d':' -f2) == $1 ]] && echo $(echo $i|cut -d':' -f1); done; }  # returns the keyword for a given pid
f_addThread(){ keyword=$1; pid=$2; threads+=( "$keyword:$pid" ); echo "added thread $keyword ($pid)"; }  # adds a thread to the array
f_removeThread(){ pid=$1; threads=( ${threads[@]/$(f_getThreadKeyword $pid):$pid} ); }  # removes a thread to the array
f_getThreadPids(){ echo ${threads[@]}|tr ' ' '\n'|cut -d':' -f2|tr '\n' ' '; }   # returns all pids


sleep 3 &
f_addThread first $!

sleep 10 &
f_addThread second $!

sleep 5 &
f_addThread third $!


while [[ $(jobs|grep -iE 'läuft|running' -c) -gt 0 ]]; do  # there are running background jobs
  wait -p next -n $(f_getThreadPids)
  err=$?
  echo pid $next exited with $err \($(f_getThreadKeyword $next)\)
  f_removeThread $next
done

echo done

Output:

added thread first (1429283)
added thread second (1429285)
added thread third (1429286)
pid 1429283 exited with 0 (first)
pid 1429285 exited with 143 (second)
pid 1429286 exited with 0 (third)

(I killed the second thread from another console)

threads in bash

Here an easy script for using threads in bash

#!/bin/bash

threads=4

thread(){
  echo "thread $$ started with param $1"
  sleep 10  # do stuff
}

selfcount(){ echo $(( $(ps -ef|grep -v grep|grep -c $0) - 3 )); }

for i in {1..100}; do   # worktasks
  while [[ $(selfcount) -ge $threads ]]; do
    sleep 0.1
  done
  thread $i &   # call thread in background
  sleep 0.1
done

while [[ $(selfcount) > 0 ]]; do sleep 0.1; done # wait for the last threads to finish

Create password for /etc/shadow

Sometimes you have to create a password-hash for the shadow-file. Here is an easy way to do it:

Method 1 (better suitable for scripting – passwort is visible)

openssl passwd -6 -salt xyz  yourpass

Method 2 (you enter in the PW – no clear text to see)

mkpasswd --method=SHA-512 --stdin

Note:
passing -1 will generate an MD5 password, -5 a SHA256 and -6 SHA512 (recommended)
The option --method accepts md5, sha-256 and sha-512

source: [stackexchange]