bashawkshdd-wrt

Bash and Awk Strange Behavior (DD-WRT)


I am testing a small script in the DD-WRT Web interface that randomizes the router's MAC address. The script uses awk to do the randomization. The script works when awk is used without the shebang (#!/bin/bash), as well as vice versa (without awk but including the shebang). However, the script does not work when both the shebang and awk is used.

Works (uses awk, but no shebang):

nvram set mac_clone_enable=1;
nvram set def_hwaddr=$(awk 'function m(n){srand(systime()+n);return":"(10+int(rand()*99));}END{print "A4"m(1)m(2)m(3)m(4)m(5);}');
nvram commit;
rc restart;

Also Works (has shebang, but no awk):

#!/bin/bash

nvram set mac_clone_enable=1;
nvram set def_hwaddr="02:44:55:66:77:88";
nvram commit;
rc restart;

Doesn't Work (shebang and awk):

#!/bin/bash

nvram set mac_clone_enable=1;
nvram set def_hwaddr=$(awk 'function m(n){srand(systime()+n);return":"(10+int(rand()*99));}END{print "A4"m(1)m(2)m(3)m(4)m(5);}');
nvram commit;
rc restart;

I need the script to use awk and have the shebang, so it can be used in a cron job. What could be the problem?


Solution

  • awk is expecting an input file. You can rewrite instead using the BEGIN block

    awk 'function r() {return ":"(10+int(rand()*99))} 
         BEGIN{srand(); print "A4" r() r() r() r() r()}'
    

    returned

    A4:72:63:62:91:102
    

    you also do not need to reinitialize random seed each time; once is enough.