Function Samples
ip 驗證
# Test an IP address for validity:
# Usage:
# valid_ip IP_ADDRESS
# if [[ $? -eq 0 ]]; then echo good; else echo bad; fi
# OR
# if valid_ip IP_ADDRESS; then echo good; else echo bad; fi
#
function is_ip()
{
local ip=$1
local stat=1
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS='.'
ip=($ip)
IFS=$OIFS
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
stat=$?
fi
return $stat
}
分割線(自動調整寬度)
CL () {
WORDS=$@; termwidth="$(tput cols)"; padding="$(printf '%0.1s' ={1..500})"; printf '%*.*s %s %*.*s\n' 0 "$(((termwidth-2-${#WORDS})/2))" "$padding" "$WORDS" 0 "$(((termwidth-1-${#WORDS})/2))" "$padding";
}
CL "This is Seperator Line"
大小寫轉換
ToUpper() {
echo $1 | tr "[:lower:]" "[:upper:]"
}
ToLower() {
echo $1 tr "[:upper:]"} "[:lower:]"
}
URL 字串編碼
function urlencode() {
local data
if [[ $# != 1 ]]; then
echo "Error: No string to urlencode"
return 1
fi
data="$(curl -s -o /dev/null -w %{url_effective} --get --data-urlencode "$1" "")"
if [[ $? != 3 ]]; then
echo "Unexpected error" 1>&2
else
echo "${data##/?}"
fi
return 0
}
urlencode "$1"
function urldecode() {
# urldecode <string>
local url_encoded="${1//+/ }"
printf '%b' "${url_encoded//%/\\x}"
}
函數回傳字串
- https://linuxhint.com/return-string-bash-functions/
- https://www.linuxjournal.com/content/return-values-bash-functions
Example-1: Using Global Variable
function F1()
{
retval='I like programming'
}
retval='I hate programming'
echo $retval
F1
echo $retval
Example-2: Using Function Command
function F2()
{
local retval='Using BASH Function'
echo "$retval"
}
getval=$(F2)
echo $getval
Example-3: Using Variable
function F3()
{
local arg1=$1
if [[ $arg1 != "" ]];
then
retval="BASH function with variable"
else
echo "No Argument"
fi
}
getval1="Bash Function"
F3 $getval1
echo $retval
getval2=$(F3)
echo $getval2
is_root
用途:檢查是否以 root 帳號執行
is_root()
{
current_user="`id`"
case "$current_user" in
uid=0\(root\)*)
;;
*)
echo "$0: You must have root privileges in order to install ${product_name}"
echo "su as root and try again"
echo
exit 1
;;
esac
}
check_os
用途:檢查 OS 版本
check_os()
{
if [ -f /etc/redhat-release ];then
rhel=`grep "^Red Hat Enterprise Linux" /etc/redhat-release`
centos=`grep "^CentOS" /etc/redhat-release`
release=`cat /etc/redhat-release | cut -d'.' -f1 | awk '{print $NF}'`
if [ ! -z "${rhel}" ];then
sys="rhel"
fi
if [ ! -z "${centos}" ];then
sys="rhel"
fi
fi
if [ -z "${sys}" -o -z "${release}" ];then
echo "Can not determine Linux distribution."
exit 127
fi
if [ -f /proc/vz/veinfo ];then
# we are under Virtuozzo
virtuozzo=1
else
virtuozzo=0
fi
if [ "${VNDEBUG}" ];then
debugrpm='--rpmverbosity=debug'
else
debugrpm=''
fi
}
IsRunning
用途:檢查自身程序是否已經執行中,如果有,程序立即跳離,可避免同一個 script 重複被執行。
IsRunning() {
if [ ! -e $script_pid ];then
RUNCOUNT=0
else
RUNPID=$(cat $script_pid)
RUNCOUNT=$(ps -fp $RUNPID | grep -c `basename $0`)
fi
#echo $RUNCOUNT
if [ $RUNCOUNT -eq 0 ];then
echo $$ > $script_pid
return 1 # return False
else
return 0 # return True
fi
}
script_pid="/tmp/$(basename $0).$DB_NAME.pid"
# Check if the program is already running.
if IsRunning
then
echo "Abort: The program is already running!"
exit 1
fi
getopts 指令參數
Usage() {
echo "Usage: $0 [-t <TEXT-Message>] [-n <phone-number>]";
echo "For example: $0 -t \"Hello, SuperMan\" -n \"085713 457199\" "
}
while getopts ":t:n:" o; do
case "$o" in
t)
t=$OPTARG
;;
n)
n=$OPTARG
;;
\?)
echo "Invalid option: -$OPTARG"
Usage
exit 1
;;
:)
echo "Option -$OPTARG requires an argument !"
Usage
exit 1
;;
esac
done
if [ $OPTIND -ne 5 ]; then
echo "Invalid options entered !"
Usage
exit 1
fi
Pause 暫停
用法: pause
可用於程式開發及偵錯
pause()
{
local force_pause=$1
if [ -z $force_pause ]; then
if test $NONINTERACTIVE; then
return 0
fi
else
shift
fi
[ $# -ne 0 ] && echo -e $* >&2
echo -e "Press [Enter] to continue...\c " >&2
read tmp
return 0
}
Log 訊息
log() { # classic logger
local prefix="[$(date +%Y/%m/%d\ %H:%M:%S)]: "
echo "${prefix} $@" >&2
}
log "INFO" "a message"
Error 錯誤訊息
用途:輸出錯誤訊息
error()
{
echo -e "Error: $*!" >&2
return 0
}
die()
{
echo
echo "ERROR: $*"
echo
echo "Check the error reason, fix and try again."
echo "You are welcome to open a support ticket at https://help.4psa.com!"
echo
rm -f ${repolocal} local$$
rm -f /var/lock/subsys/vninstaller
exit 1
}
check_deps()
{
which yum >/dev/null 2>&1
if [ $? -gt 0 ];then
echo "yum binary can not be found."
die "It's not in the system PATH or in a standard location."
fi
which ifconfig >/dev/null 2>&1
if [ $? -gt 0 ];then
yum -y install net-tools >/dev/null 2>&1
if [ $? -gt 0 ];then
echo "ifconfig binary can not be found and package net-tools could not be installed."
die "It's not in the system PATH or in a standard location."
fi
fi
}
詢問 Yes/No
用法: getyn "Would you like to install WANPIPE now? [y]"
$NONINTERACTIVE 如果程式執行時,不想讓 user 做任何的輸入時,可以為 1
NONINTERACTIVE=1 ,或者 = 空白,以顯示相關的提示訊息
prompt()
{
if test $NONINTERACTIVE; then
return 0
fi
echo -ne "$*" >&2
read CMD rest
return 0
}
getyn()
{
if test $NONINTERACTIVE; then
return 0
fi
while prompt "$* (y/n) "
do case $CMD in
[yY]) return 0
;;
[nN]) return 1
;;
*) echo -e "\nPlease answer y or n" >&2
;;
esac
done
}