What are the rules to write robust shell scripts?

前端 未结 2 823
情歌与酒
情歌与酒 2021-02-02 18:00

I recently erased part of my home directory with a shell script I wrote. Fortunately, I did hit Ctrl-C fast enough to avoid the worst.

My mistake h

2条回答
  •  一向
    一向 (楼主)
    2021-02-02 18:41

    General rule: you need to think about the stuff you are doing. Testing and debugging is a way to achieve the success.

    Always decompose the problem, regardless of the language you are using. Write small procedures. Test them. Fix if necessary. Write more complicated ones using the small ones. And so one.

    Learn about the debugging tools in a given language. In bash the -x option can do a wonders for you. Also, strategically placed echo foo or echo $variable can help you a lot.

    If you need to do something potentially destructive (like removing the files) make a dry-run first. Replace all rm with echo and check the results. If something wrong happened, you will see that in the list of files-to-be-removed.

    Test every step of data preparation. Even, if you write a one-liner in bash, check the result of each stage, before adding a pipe and another stage. Detect problems early and fix them early.

    Make sure, the solution is scalable. If it worked for you for 20 data items, will it worked for 20 thousands?

    If your program processes data given by user, make sure it would behave in a sane way even for garbage on input. Reporting an error and exiting is a sane way in such cases.

    Aim for simplicity. The simpler the solution, the easier you can avoid mistakes.

    And - for sure - I forgot about adding something important here :)

    Good luck in your coding!

提交回复
热议问题