[shell]如何跨shell指令碼檔案呼叫函式
問題背景
在寫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環境中,讀取和執行檔案中的命令,並返回最後一行的退出狀態