Shell script structure Example 1, shell script example
Since 2013, I have been lazy and have written a lot less. This year, I plan to summarize my previous accumulated experience.
Start with shell.
After nearly three years of game O & M, I often write some shell scripts during the period. Many scripts actually have many reusable parts.
According to your own style, if it is an important script, the script content can be divided into three parts: the input part, the core logic part, and the output part.
This article mainly introduces the input section.
Generally, scripts running on the current network are recommended to include parameters to prevent them from being executed. For example:
Test. sh-w 1
The script with parameters is written as follows, and the comments are written in the personal style:
#!/bin/bash
# creat by fank 2016-01-01
echo "===`date +"%F %T"`=="
while getopts w: opt;docase $opt in w) w_list=${OPTARG};; ?) usage;;esacdone
Usage (){
Echo "$0-w [check_list]"
Echo "$0-w \" 27-30 \""
Echo "$0-w \" 2, 3, 4 \""
Exit 1
}
echo $w_list
After entering parameters, you can perform Parameter Parsing or checking.
In the actual process, you may also often encounter parameter extensions. For example, if you input-w '1-10', how can you save it as an array containing 1-10 in the script:
function check_input(){ [[ -z $w_list ]]&& usage w_list=${w_list//-/..} w_tmp="echo {$w_list}" list=$(eval $w_tmp) list=$(echo $list|awk -F'{|}| ' '{for(i=1;i<=NF;i++)print $i }'|xargs) for i in $list;do [[ $((i+0)) != $i ]] && tms_fail "Input worldID must be a number!" done echo "World set list is as follows:" echo $list echo "=="}
In the above Code, replace the w_list variable (string)
w_list=${w_list//-/..}
Then a sequence is generated by using curly braces extension and stored in the new variable.
w_tmp="echo {$w_list}" list=$(eval $w_tmp)
In fact, this Code also applies to-w'1, 2, 3 'input.