It would be safer to do a Alt+SysRq+(R,E,I,S,U,B or O) than force a hard reboot.
- R Switch the keyboard from raw mode to XLATE mode
- E SIGTERM everything except init
- I SIGKILL everything except init
- S Syncs the mounted filesystems
- U Remounts the mounted filesystems in read-only mode
- B Reboot the system, or O Turn off the system
You could just Alt+SysRq+B/O to reboot/halt if you really wanted to but you put your filesystems at risk by doing so. Doing all of the above is relatively safe and should work even when the rest of the system has broken down.
This is essentially the same method you're talking about in your commands but I'm not sure you could script the E and I (as they'll nuke your terminal access). But you could definitely handle the disk access and reboot or shutdown.
for i in s u b; do echo $i | sudo tee /proc/sysrq-trigger; sleep 5; done # reboot
for i in s u o; do echo $i | sudo tee /proc/sysrq-trigger; sleep 5; done # halt
You could still lose data from running applications but it shoudn't knacker your filesystem. If you have particularly huge disk write caches it might be best to increase the