In a Linux environment (including Cygwin in the appropriate simulation environment, such as Windows), you will slowly accumulate some of your own small scripts to speed up the daily operation and workflow, such as automatic mount and unload USB drive, Map network drive, data backup and recovery. In order for these scripts to be consistent in their style of help documents, informational cues, command-line arguments, you need to design a template. The basic ideas are as follows:
- Make a display_help function. When the script is run with the-h parameter, the function is called to display the basic usage of the script, explaining the documentation and usage examples.
- Command-line arguments that can handle single-character characters.
- For different operating systems and host names to do the appropriate operation. This way, you can ensure that the same script runs on multiple computers on its own in different ways. For example, I have written a file synchronization script based on Rsync, which realizes the synchronization and backup between three computers.
- Hints, warnings, and error messages during a script run are identified with different string prefixes, making them easier to identify.
Based on the above considerations, the script template is created as follows:
#!/bin/Bashscript_name=""script_usage=$ (Cat <<Eofdescription of script usage. EOF) script_function=$ (Cat <<Eofdescription of scriptfunction. EOF) script_doc=$ (Cat <<Eofscript documentation.-H Display this help. EOF) script_examples=$ (Cat <<Eofscript examples. EOF) state_prefix="==="warning_prefix="***"error_prefix="!!!"functionDisplay_help () {if [-N"$script _usage" ];ThenEcho-e"Usage: $script _usage"Fiif [-N"$script _function" ];ThenEcho-e"$script _function"Fiif [-N"$script _doc" ] ;ThenEcho-e"\n$script_doc"Fiif [-N"$script _examples" ];ThenEcho-e"\nexamples"Echo-e"$script _examples"Fi}# Process Command OptionsWhile Getopts": H"OPT;DoCase $optInchh) Display_help exit0;; \?) Display_help exit1;;EsacDoneShift $ ($OPTIND-1) # Start Execute the commandif [$OSTYPE =‘Cygwin'] && ['Hostname ' ="xxxthen exit 0fiif [$OSTYPE = "&& [' hostname ' = "xxx"]; then exit 0fi $warning _ Prefix Operating system or host name is not supported!
The Bash script template I used