问题背景
在写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 filenameRead and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename.
在当前shell环境中,读取和执行文件中的命令,并返回最后一行的退出状态