您的位置:首页 > 运维架构 > Shell

[shell]如何跨shell脚本文件调用函数

2016-07-15 23:09 344 查看

问题背景

        在写shell代码的过程中,遇到一件低效率的事情。
写三个日志打印函数,在很多文件中很多次使用。但是不想每个文件都定义一次。
比如代码如下:
function LOG_NOTICE()
{
echo -e "\033[34m${1}\033[0m"
}

function LOG_ERROR()
{
echo -e "\033[4m\033[1m\033[33mERROR:\033[0m\033[33m${1}\033[0m"
}

解决方案

   将如上代码定义到文件中,比如log.sh
   利用source ./log.sh后调用
   log.sh文件内容如下
#!/bin/bash

function LOG_NOTICE() { echo -e "\033[34m${1}\033[0m" } function LOG_ERROR() { echo -e "\033[4m\033[1m\033[33mERROR:\033[0m\033[33m${1}\033[0m" }


   调用函数的内容如下:
#!/bin/bash

source ./log.sh

LOG_NOTICE "NOTICE"
LOG_NOTICE "ERROR"

延伸

source filename
Read  and  execute commands from filename in the current shell environment and return the exit status of the last command executed from filename.
在当前shell环境中,读取和执行文件中的命令,并返回最后一行的退出状态
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: