Modular and script reuse of shell scripts

Source: Internet
Author: User


It's not uncommon to write shell scripts on a daily basis, so many shells have been written,how can we use them when we meet the related processing functions that we've written? Is it a direct copy of the code or a "reference", or how to modularize a complex function call when writing a relatively complex shell?

How to import multiplexing and modularity is what you learn together here.

We will follow the following sections to learn:

1, the shell execution method different effect is different

2. Import Module


1, the shell execution method different effect is different

The first type:sh test.sh

this way, in our current session, we will create a new child to execute the test.sh script. What we can get is the result or output of this test.sh execution.

[Email protected]:~ #more test.sh

#!/bin/bash

s= "thisis a test file"

[Email protected]:~ #sh test.sh

[Email protected]:~ #echo $s

[Email protected]:~ #sh test.sh

[Email protected]:~ #echo $?

0

The second type:sourcetest.sh or . test.sh

This approach is equivalent to copying the contents of the test.sh into the current process to execute. So what we can get is not just the result of the completion of this test.sh execution. We can also get the global variables defined in this script, the function functions defined. Because we are copying the contents of the script into the current file.

That way is similar to the module import in many of our programming languages. Let's verify that it's not.

[Email protected]:~#. test.sh

[Email protected]:~ #echo $s

This is atest file

[Email protected]:~ #s =0

[Email protected]:~ #echo $s

0

[Email protected]:~ #source test.sh

[Email protected]:~ #echo $s

This is a test file

#我们可以看到这里, you can get the contents of the variable S.


2. Import Module

2.1) Pilot into one of the simplest

Based on the second of the two shell execution methods we mentioned in the 1th above . We use this "copy" feature to enable the ability to import previously written functions

For example, we wrote a simple format for the output log function:

[email protected]:~# Cat test1.sh

#!/bin/bash

modulename=$ (basename $ 0)

logfile=/tmp/logfile-' date +%y%m%d '

{

  #[2017-03-31 12:00:00]-textname-the log message

  localdatetime= ' Date "+%y-%m-%d%h:%m:%s" '

  if["$"];then

    echo "[${datetime}]-${modulename}-$ | Tee-a${logfile}

    return 1

}


the above log_info function will format and brush out our log content. We can reuse it in multiple places.

we're here. main.sh Scripts and test1.sh are in the same directory. We main.sh import the contents of test1.sh first, and then use the variables and functions that are already in test1.sh. Let's look at the contents of main.sh.

[Email protected]:~# cat main.sh

#!/bin/bash

# We're here to pass . test1.sh or source test1.sh the way to import test1.sh in.

. test1.sh

Main ()

{

# We can use the Log_info function directly here .

Log_info ' This is the main shell '

}

Main

[Email protected]:~#./main.sh

[2017-03-31 15:11:23]-main.sh-this isthe main shell

[Email protected]:~# more/tmp/logfile-20170331

[2017-03-31 15:11:39]-main.sh-this isthe main shell


2.2) If we need to import other functions from somewhere else

above our main and test1 are in the same directory, so we use a relative path in main. If we need to import the "module"test1.sh is placed in the other directory? Or is there a hierarchical relationship between our modules? How are we supposed to introduce them?

1) because we are introducing, the system will find the file we want to import by default in the environment variable $PATH . One approach is to put the public modules that we need to use in the path $PATH contains. Or we add a common path to the $PATH environment variable, and then put the public modules we need to use under the public folder.

Such as:

[Email protected]:~/test_shell# cat main.sh

#!/bin/bash

. test1.sh

. config.sh

Main ()

{

Log_info ' This is the main shell '

Readconf

ECHO${CONF}

}

Main

[Email protected]:~/test_shell# Echo$path

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

#在这里我们可以看到我们将两个模块放在了PATH的路径下面.

[Email protected]:~/test_shell# ls/usr/local/bin/test1.sh

/usr/local/bin/test1.sh

[Email protected]:~/test_shell# ls-l/usr/local/bin/config.sh

-rw-r--r--1 root root 15:41/usr/local/bin/config.sh


Here I copy the file directly into the directory $PATH contains.

2) We export the absolute path where the module is located to the path :

such as :

[Email protected]:~/test_shell/module#pwd

/root/test_shell/module

[Email Protected]:~/test_shell/module#tree

.

├── config.sh

└── test1.sh

0 directories, 2 files

[Email protected]:~/test_shell/module# CD. /

[Email protected]:~/test_shell# moremain.sh

#!/bin/bash

#这里我们给了一个绝对路径

Modupath=/root/test_shell/module

Export path= $PATH: ${modupath}

. test1.sh

. config.sh

Main ()

{

Log_info ' This is the main shell '

Readconf

ECHO${CONF}

}

Main


3) Dynamic Loading module

of course, if we were to write a shell with a relatively complex function , we would package this whole complex, structurally-related shell and copy it to any place to execute it. So we have no way of knowing in advance what our absolute path is. For example, this directory structure:

[Email protected]:~/test_shell#pwd

/root/test_shell

[Email Protected]:~/test_shell#tree

.

├── main.sh

├── Module

│ ├── config.sh

│ └── test1.sh

└── Module2

└── mail.sh

2directories, 4 files

[Email Protected]:~/test_shell#more main.sh

#!/bin/bash

# Here we dynamically get to our absolute path and put together the path of the module.

modupath=$ (dirname$ (readlink-f))/module

Echo${modupath}

Exportpath= $PATH: ${modupath}

. test1.sh

. config.sh

Main ()

{

Log_info ' This is the main shell '

Readconf

Echo ${conf}

}

Main


4) How to avoid importing a module repeatedly

we have to say that source, in fact, is to copy the content to the same place to execute, then we can add a judgment condition in the module. If we find that a variable in our module already exists, we return it and no longer import the subsequent content.

such as this:

[Email Protected]:~/test_shell#more module/test1.sh

#!/bin/bash

# What I've commented out here is. And this variable name, as far as possible according to some rules to ensure that the variable name is unique.

#if [${m_log}];then

# return 0

#fi

#m_log = "M_log"

# This line of output is to test if it has been imported more than once.

echo "TEST is"

modulename=$ (basename$0)

logfile=/tmp/logfile-' date+%y%m%d '

Log_info ()

{

#[2017-03-31 12:00:00]-textname-the logmessage

Datetime= ' Date ' +%y-%m-%d%h:%m:%s "'

If ["$"];then

echo "[${datetime}]-${modulename}-$ | Tee-a ${logfile}

Else

Return 1

Fi

}


Here we are commenting out the case, to see how many times the import is the reaction.

[Email protected]:~/test_shell# more main.sh

#!/bin/bash

modupath=$ (DirName $ (readlink-f$0))/module

Echo ${modupath}

Export path= $PATH: ${modupath}

. test1.sh

. config.sh

Main ()

{

Log_info ' This is the main shell '

Readconf

ECHO${CONF}

}

Main

[Email protected]:~/test_shell# moremodule/config.sh

#!/bin/bash

. test1.sh

Readconf ()

{

conf= "Read the config file"

}

[Email protected]:~/test_shell#./main.sh

/root/test_shell/module

TEST is

TEST is

[2017-03-31 16:51:09]-main.sh-this isthe main shell

Read the config file

#我们可以看到这里多次输出了TEST is content.


# Remove What we have commented out above, and now import it more than once, but essentially only once. This also avoids multiple circular references.

[Email protected]:~/test_shell#./main.sh

/root/test_shell/module

TEST is

[2017-03-31 16:56:31]-main.sh-this isthe main shell

Read the config file

#当我们去掉了注释部分, there will be no repeated loading.


-----------------------------Summary-----------------

In fact, this module reuse, in fact, is through source or. The way the original module content "copy", but in the process of use, you need to pay attention to the problem of the module path, there are levels, and multiple calls.

As for the complex shell, I think the basic is not too complicated to accept, basically in accordance with a certain organizational hair way can become clear. and improve reuse.

You can accumulate some of the more commonly used functions, need to use the time, import, do not have to write repeatedly. such as logs, email alerts and so on.

----------------------------------------------------



This article is from the "Start from scratch" blog, be sure to keep this source http://atong.blog.51cto.com/2393905/1912179

Modular and script reuse of shell scripts

Related Article

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.