[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: scripting problem



On Sat, Nov 26, 2005 at 08:16:31PM +0100, John Smith wrote:
> 	does somebody know why I keep losing the first character of the
> third resulting string?
> 
> =======================================================
> 
> user@testbox:/home/user/tmp >cat t4.sh
> #!/bin/sh
> 
> export INPUT='$1$iW95z/HB$GFcYFxMKK6x8EUPglVkux.'
> 
> echo "1 ==="$INPUT"==="
> 
> export MD5PW=$(echo -n "$INPUT" |  hexdump -v -e '" " 1/1 "%02d"')
> 
> echo "2 ==="${MD5PW}"==="
> 
> echo -n "3 ===";echo -n ${MD5PW} | tr ' ' '\n' | while read char ; do awk '{printf("%c",$char)}' ; done ; echo "==="
> user@testbox:/home/user/tmp >./t4.sh
> 1 ===$1$iW95z/HB$GFcYFxMKK6x8EUPglVkux.===
> 2 === 36 49 36 105 87 57 53 122 47 72 66 36 71 70 99 89 70 120 77 75 75 54 120 56 69 85 80 103 108 86 107 117 120 46===
> 3 ===1$iW95z/HB$GFcYFxMKK6x8EUPglVkux.===

There are two issues with this ;)

Firstly, the "while read ..." loop is not only superfluous, it's
exactly what's causing the strange effect you're observing.  What
happens is that "read char" reads one line from stdin and puts it in
$char.  Next, more or less unrelated, awk starts up, and consumes the
remaining lines on stdin all by itself, and executes the given printf
command for every line -- that's standard awk behaviour.  Then, the
loop is done, 'cos there's nothing left on stdin.  And, as the first
line had already been removed by "read", awk simply never got it...
So, a first improvement would be to write

echo -n "3 ===";echo -n ${MD5PW} | tr ' ' '\n' | awk '{printf("%c",$char)}' ; echo "==="

So far so good, but what's this $char?  As the whole awk command is in
single quotes, the shell won't interpolate anything for $char (in case
that's what was originally intended).  Strangely enough, you could just
as well write $foo, or $anything, and still get the same result. 
Apparently, awk is simply substituting $0 (the line read from stdin),
if it encounters anything it doesn't know what to do with (not sure
though, what exactly is going on here...(?))

Anyway, if you put $0 (or $1 (=the first field) -- both are identical
in this particular case) in place of $char, things should be fine

echo -n "3 ===";echo -n ${MD5PW} | tr ' ' '\n' | awk '{printf("%c",$0)}' ; echo "==="

Cheers,
Almut



Reply to: