hush-shell / hush

Hush is a unix shell based on the Lua programming language
MIT License
658 stars 23 forks source link

Odd behaviour with overwrite then append in command block #19

Closed loserMcloser closed 2 years ago

loserMcloser commented 2 years ago

Running the following hush script multiple times results in unexpected behaviour.

test.hsh

#!/usr/bin/env hush

let now = ${ date "+%s" }.stdout
let stripped_now = std.split(now, "\n")[0]
let arr = [ "1", "2" ]
{
    echo $stripped_now > test_file;
    echo $arr >> test_file
}

Run once


$ ./test.hsh; cat test_file
1652491810
1 2

Run twice

$ rm test_file; ./test.hsh; cat test_file; sleep 2; echo "************"; ./test.hsh; cat test_file
1652491824
1 2
************
1652491827
1 2
1 2

Huh? Notice the time has changed, but now there are two copies of the array at the end of the file...?

Run three times

$ rm test_file; ./test.hsh; cat test_file; sleep 2; echo "************"; ./test.hsh; cat test_file; sleep 2; echo "************"; ./test.hsh; cat test_file
1652491843
1 2
************
1652491845
1 2
1 2
************
1652491847
1 2
1 2
1 2

Again the time is changing in subsequent runs, but now there are three copies of the array appended after the third run.

Run three times with an extra append before the third

% rm test_file; ./test.hsh; cat test_file; sleep 2; echo "************"; ./test.hsh; cat test_file; sleep 2; echo "************"; echo "hi there" >> test_file; ./test.hsh; cat test_file 
1652491862
1 2
************
1652491864
1 2
1 2
************
1652491866
1 2
1 2
hi there
1 2

How did the "hi there" end up in the file? The file test_file should be completely overwritten each time test.hsh is run by the first line in the command block of the script.

I'm really confused....

gahag commented 2 years ago

Thanks for the great bug report! I missed the truncate flag when opening the file for the > redirection, so it was actually overwriting just the first bytes instead of the whole file. I'll publish the fix asap.