Showing posts with label Bourne shell. Show all posts
Showing posts with label Bourne shell. Show all posts

Tuesday, September 6, 2016

Bourne shell: Generating Random Number without Modulo Bias

Command: 

$ cat rand_nobias.sh


Result:

#!/bin/sh

numlines=$1;
randmax=32767;
max=$((($randmax/$numlines)*$numlines)); 
rand=$RANDOM;

until [ $rand -lt $max ] 
do 
rand=$RANDOM;
done 


echo $rand;

Tuesday, February 2, 2016

AWK: Calling Bash Version of echo Command with \c Option

I don't know how to embed Bourne shell echo with \c option inside AWK script, so I did this way.

echo.bash

#!/bin/bash
for i; do
echo -n $i
done


AWK script using above echo.bash script, so you can call bash version of echo:

$ awk -F, '{
cmd="./echo.bash \""$2"\" | openssl dgst -sha256"
while (cmd | getline line){
print line
}
close(cmd)
}' ./test.txt

Monday, February 1, 2016

The Difference Between Bash and Bourne Shell When Using echo Command

Bash

$ echo -n "A. P. Balachandran" | md5
b9114dc37ab93677d533a0e3e025ee58

Bourne shell: Same value!

sh-3.2$ echo "A. P. Balachandran\c" | md5
b9114dc37ab93677d533a0e3e025ee58

Bourne shell: wrong md5 value!

sh-3.2$ echo -n "A. P. Balachandran" | md5
9e63b57c592863eaad63d37f72bce0d0

Bourne shell: -n option isn't working. That is why.

sh-3.2$ echo -n "A. P. Balachandran"
-n A. P. Balachandran

Saturday, January 30, 2016

Debugging: Cron: % sign

Error message:

/bin/sh: -c: line 0: unexpected EOF while looking for matching `]'
/bin/sh: -c: line 1: syntax error: unexpected end of file


The source code:

*/10 * * * * perl -le 'sleep rand 60' && head -$[${RANDOM} % `wc -l < /Users/username/lines.txt` + 1] /Users/username/lines.txt | tail -1 | ruby /Users/username/tweet.rb

Crontab man page:

The entire command portion of the line, up to a newline or % character, will be executed by /bin/sh or by the shell specified in the SHELL variable of the cronfile. Percent-signs (%) in the command, unless escaped with backslash (\), will be changed into newline characters, and all data after the first % will be sent to the command as standard input.

Fixed source code:

*/10 * * * * perl -le 'sleep rand 60' && head -$[${RANDOM} \% `wc -l < /Users/username/lines.txt` + 1] /Users/username/lines.txt | tail -1 | ruby /Users/username/tweet.rb