Reading password in Unix shell


print -n "Enter Your password:"
stty_orig=`stty -g`
trap "stty ${stty_orig}; exit" 1 2 3 15
stty -echo >&- 2>&-
read PASS
stty ${stty_orig} >&- 2>&-
trap 1 2 3 15
print

trap :catches interruptions. I.e. if the user presses Ctrl+C, the normal stty mode is set before stopping the program
stty -echo :switches off the display echo
>&- 2>&- :helps to avoid “stty: Not a typewriter” message for non-interactive scripts.

Unix shell: workaround for loop problem

It’s not possible to get the value of the loop variables in some versions of ksh.

Example:

#!/bin/ksh

num=0
cat $0 | while read line ; do
let num=num+1
done

echo "Number=$num"

This script will return “Number=0” as the result on some Linux machines.

Here is the workaround for the problem: You should change the redirection method for the input file.

#!/bin/ksh

l=0
while read line ; do
let l=l+1
done < $0 echo "Number=$l"

The last script will return the correct result: "Number=9"

Another possibility is to use the named pipe:

#!/bin/ksh

TMPPIPE=/tmp/thepipe.$$
mkfifo $TMPPIPE
cat $0 > $TMPPIPE &
num=0
while read line ; do
let num=num+1
done < $TMPPIPE echo "Number=$num"