Shell script structure Example 1, shell script example

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.