原文地址:一些方便系统诊断的bash函数

 一些方便系统诊断的bash函数:http://hongjiang.info/common-bash-functions/
这段脚本包含100多个bash函数,是我几年前方便自己调试和诊断问题写的。贴出来给有需要的人,因为比较懒怎么使用这些函数就不写说明了。其中以下划线开头的是表示私有函数,以cf_开头的表示公共函数,可当做命令使用。
# check current os is linux
function cf_is_linux() {
[[ "$OSTYPE" = *linux* ]] && echo "true" && return
echo "false" && return
} # check current os is mac/darwin
function cf_is_darwin() {
[[ "$OSTYPE" = *darwin* ]] && echo "true" && return
echo "false" && return
} # check current os is windows/cygwin
function cf_is_cygwin() {
[[ "$OSTYPE" = *cygwin* ]] && echo "true" && return
echo "false" && return
} function cf_is_gnu_date() {
date --version >/dev/null >& && echo "true" && return
echo "false" && return
} function cf_is_gnu_sed() {
sed --version >/dev/null >& && echo "true" && return
echo "false" && return
} function cf_is_gnu_awk() {
awk --version | grep GNU >/dev/null && echo "true" && return
echo "false" && return
} function cf_is_gnu_grep() {
grep --version | grep GNU >/dev/null && echo "true" && return
echo "false" && return
} # java style startsWith
function cf_starts_with() {
local str=$
local pre=$
[[ "$str" == ${pre}* ]]
} # java style substring
function cf_substring() {
local str=$
local begin=$
local end=$
if [ -z "$end" ]; then
echo ${str:$begin}
else
local len=`expr $end - $begin`
echo ${str:$begin:$len}
fi
} # get current shell name
function cf_shell_name() {
local name=$( ps -ocommand= -p $$ | awk '{print $1}')
if cf_starts_with $name "-"; then
cf_substring $name
else
echo $name
fi
} # check current shell is bash
function cf_is_bash() {
[[ `cf_shell_name` = "-bash" || `basename $(cf_shell_name)` = "bash" ]] && echo "true" && return
echo "false" && return
} # check current shell is zsh
function cf_is_zsh() {
[[ `cf_shell_name` = "-zsh" || `basename $(cf_shell_name)` = "zsh" ]] && echo "true" && return
echo "false" && return
} function _script_dir() {
if cf_is_bash >/dev/null; then
cd "$( dirname "${BASH_SOURCE[]}" )" && pwd -P
elif cf_is_zsh >/dev/null; then
cd "$( dirname "${(%):-%N}" )" && pwd -P
else
echo "unsupported shell" && return
fi
} function _script_file() {
if cf_is_bash >/dev/null; then
basename "${BASH_SOURCE[0]}"
elif cf_is_zsh >/dev/null; then
basename "${(%):-%N}"
else
echo "unsupported shell" && return
fi
} # colorful grep. private function
function _get_colorful_grep() {
cf_is_gnu_grep >/dev/null && echo "grep --color" && return
export GREP_OPTIONS='--color=always'
export GREP_COLOR='1;35;40'
echo "grep"
} # list all common functions
function cf_functions() {
if cf_is_bash >/dev/null; then
declare -F | awk '{print $NF}' | grep "cf_" | sort
elif cf_is_zsh >/dev/null; then
print -l ${(ok)functions} | grep "cf_" | sort
else
echo "unsupported shell" && return
fi
} # get total memory (MB)
function cf_mem_total() {
if cf_is_linux >/dev/null; then
free -m | awk '/^Mem/{print $2"M"}'
elif cf_is_darwin >/dev/null; then
sysctl hw.memsize | awk '{print $2/1024/1024"M"}'
else
echo "unsupported os" && return
fi
} # decimal to hexadecimal
function cf_dec2Hex() {
printf "%x" $
} # decimal to octal
function cf_dec2Oct() {
printf "%o" $
} # decimal to binary
function cf_dec2Bin() {
echo "obase=2; $1" | bc
} # hexadecimal to decimal
function cf_hex2Dec() {
echo $((#$))
} # octal to decimal
function cf_oct2Dec() {
echo $((#$))
} # binary to decimal
function cf_bin2Dec() {
echo $((#$))
} function cf_calc() {
local exp="$1"
echo "$exp" | bc -l | awk '{printf "%.2f", $0}'
} # warning and exit, not for interactive shell
function cf_die() {
local msg="$1"
local code=${:-}
echo "$msg" && exit $code
} # highlight key words from file or pipeline
function cf_highlight() {
local keyword="$1"
local cgrep="$(_get_colorful_grep)"
if [ -p /dev/stdin ]; then
# from pipeline
while IFS='' read line; do
echo $line | eval "$cgrep -E \"${keyword}|$\""
done
else
local file="$2"
eval "$cgrep -E \"${keyword}|$\"" "$file"
fi
} function cf_ps_env() {
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return if cf_is_linux >/dev/null; then
xargs --null --max-args= < /proc/$pid/environ
elif cf_is_darwin >/dev/null; then
ps -wwE -p $pid
else
echo "unsupported os" && return
fi
} # get bash(current shell) major version
function cf_bash_major_ver() {
echo ${BASH_VERSINFO[]}
} # get bash(current shell) minor version
function cf_bash_minor_ver() {
echo ${BASH_VERSINFO[]}
} # get kernel version
function cf_kernel_ver() {
if cf_is_linux >/dev/null; then
uname -r | cut -d'-' -f1
elif cf_is_darwin >/dev/null; then
uname -r | cut -d'-' -f1
else
echo "unsupported os" && return
fi
} # get kernel major version
function cf_kernel_major_ver() {
if cf_is_linux >/dev/null; then
uname -r | awk -F'.' '{print $1"."$2}'
elif cf_is_darwin >/dev/null; then
uname -r | awk -F'.' '{print $1"."$2}'
else
echo "unsupported os" && return
fi
} # get kernel minor version
function cf_kernel_minor_ver() {
if cf_is_linux >/dev/null; then
uname -r | awk -F'.' '{print $3}'
elif cf_is_darwin >/dev/null; then
uname -r | awk -F'.' '{print $3}'
else
echo "unsupported os" && return
fi
} # get value from config file such as app.properties
function cf_get_property() {
local file="$1"
local key="$2"
grep "^${key}=" "$file" | tr -d '\r' | cut -d'=' -f2 | cf_trim
} # get command path, eg: `cf_command_path ls` output /usr/bin/ls
function cf_command_path() {
local cmd=$
cf_is_bash && builtin type -P $cmd && return $? if [ -x /usr/bin/which ]; then
local p=$( /usr/bin/which $ | head - )
[ ! -z "$p" ] && echo $p && return
return
else
local p=$( which $ | grep "^/" | head - )
[ ! -z "$p" ] && echo $p && return
return
fi
} # get all ip addresses
function cf_ip_list() {
if [ -x /sbin/ip ]; then
local list=$(/sbin/ip -o - addr list | awk '{print $4}' | cut -d'/' -f1 | tr '\n' ',')
else
local list=$(/sbin/ifconfig | grep "inet " | awk '{print $2}' | sed 's/addr://' | tr '\n' ',')
fi
echo ${list%,}
} function cf_stdio() {
local pid=$
/usr/sbin/lsof -a -p $pid -d ,,
} function cf_stdout() {
local pid=$
if cf_is_linux >/dev/null; then
readlink -f /proc/$pid/fd/
elif cf_is_darwin >/dev/null; then
/usr/sbin/lsof -a -p $pid -d | awk 'NR>1{print $NF}'
else
echo "unsupported os" && return
fi
} # get file last modification time
function cf_last_modification() {
local file="$1"
if [[ $OSTYPE == *linux* ]];then
date +%Y%m%d%H%M%S -r $file
elif [[ $OSTYPE == *darwin* ]];then
stat -f "%Sm" -t "%Y%m%d%H%M%S" $file
fi
} # check current user is root
function cf_is_root() {
[ `whoami` = "root" ] && echo "true" && return
echo "false" && return
} # check current shell is interactive
function cf_is_interactive_shell() {
if cf_is_bash >/dev/null; then
[[ "$-" = *i* ]] && echo "true" && return
elif cf_is_zsh >/dev/null; then
[[ -o interactive ]] && echo "true" && return
else
echo "unsupported shell" && return
fi
echo "false" && return
} # check current shell is login shell
function cf_is_login_shell() {
if cf_is_bash >/dev/null; then
shopt -q login_shell && echo "true" && return
elif cf_is_zsh >/dev/null; then
[[ -o login ]] && echo "true" && return
else
echo "unsupported shell" && return
fi
echo "false" && return
} # check command is exists
function cf_is_command_exists() {
local cmd=$
if [ -x /usr/bin/which ]; then
/usr/bin/which $cmd >/dev/null >& && echo "true" && return
else
which $cmd >/dev/null >& && echo "true" && return
fi
echo "false" && return
} # check file name globbing flag
function cf_is_glob_enabled() {
if cf_is_bash >/dev/null; then
[[ $- != *f* ]] && echo "true" && return
elif cf_is_zsh >/dev/null; then
[[ -o glob ]] && echo "true" && return
else
echo "unsupported shell" && return
fi
echo "false" && return
} # enable file name globbing
function cf_enable_glob() {
cf_is_bash >/dev/null && set +f && return
cf_is_zsh >/dev/null && set -o glob && return
echo "unsupported shell" && return
} # disable file name globbing
function cf_disable_glob() {
cf_is_bash >/dev/null && set -f && return
cf_is_zsh >/dev/null && set -o noglob && return
echo "unsupported shell" && return
} # check extglob flag
function cf_is_extglob_enabled() {
if cf_is_bash >/dev/null; then
shopt -q extglob && echo "true" && return
elif cf_is_zsh >/dev/null; then
[[ -o kshglob ]] && echo "true" && return
else
echo "unsupported shell" && return
fi
echo "false" && return
} # enable extglob
function cf_enable_extglob() {
cf_is_bash >/dev/null && shopt -s extglob && return
cf_is_zsh >/dev/null && set -o kshglob && return
echo "unsupported shell" && return
} # disable extglob
function cf_disable_extglob() {
cf_is_bash >/dev/null && shopt -u extglob && return
cf_is_zsh >/dev/null && unsetopt kshglob && return
echo "unsupported shell" && return
} # check pid is exists
function cf_is_pid_exists() {
local pid=$
[ -z "$pid" ] && echo "false" && return
kill - $pid >/dev/null >& && echo "true" && return
echo "false" && return
} function cf_is_java() {
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
ps -ocommand= -p$pid | awk '$1~/java$/' > /dev/null && echo "true" && return
echo "false" && return
} function cf_is_available_port() {
local port=$
if [[ "$OSTYPE" = *linux* ]];then
local r=$( netstat -ant | awk '$6=="LISTEN" && $4~":'$port'$"' )
elif [[ "$OSTYPE" = *darwin* ]];then
local r=$( netstat -ant | awk '$6=="LISTEN"' | grep "\.$port " )
else
echo "unknown system" && return
fi [ -z "$r" ] && echo "true" && return ;
echo "false" && return # port has been used
} function cf_defined() {
if cf_is_bash >/dev/null; then
[[ ${!-X} == ${!-Y} ]]
elif cf_is_zsh >/dev/null; then
[[ ${(P)-X} == ${(P)-Y} ]]
else
echo "unsupported shell" && return
fi
} function cf_has_value() {
cf_defined $ || return
if cf_is_bash >/dev/null; then
[[ -n ${!} ]] && return
elif cf_is_zsh >/dev/null; then
[[ -n ${(P)} ]] && return
fi
return
} function cf_has_sudo_privilege() {
# do not need password
sudo -n echo >/dev/null >&
} function cf_timestamp() {
date +%F-%T | tr ':-' '_' #2015_12_01_22_15_22
} function cf_length() {
echo ${#}
} # trim string
function cf_trim() {
if [ -p /dev/stdin ]; then
while IFS='' read line; do
_trim "$line"
done
else
_trim "$1"
fi
} # private function
function _trim() {
local str="$1"
local extglob=$(cf_is_extglob_enabled)
if cf_is_bash >/dev/null || cf_is_zsh >/dev/null; then
[ $extglob = "false" ] && cf_enable_extglob
str="${str##*( )}"
str="${str%%*( )}"
[ $extglob = "false" ] && cf_disable_extglob
else
echo "unsupported shell" && return
fi
echo $str
} function cf_lower() {
echo "$1" | tr '[:upper:]' '[:lower:]'
} function cf_upper() {
echo "$1" | tr '[:lower:]' '[:upper:]'
} function cf_ps_name() {
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
if cf_is_java $pid >/dev/null; then
local main=$(cf_ps_java_main $pid)
echo "java($main)"
else
ps -ocommand= -p $pid | awk '{print $1}'
fi
} function cf_ppid() {
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
ps -oppid= -p $pid
} function cf_ps_java_main() {
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
ps -ocommand= -p $pid | tr ' ' '\n' | awk '/-classpath|-cp/{getline;next};/^-/{next}1' | awk 'NR==2'
} function cf_ps_time() {
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return local elapsed="$(ps -oetime= -p $pid | cf_trim)"
local started="$(ps -olstart= -p $pid | cf_trim)"
if [ `cf_is_gnu_date` = "true" ]; then
started=$(date +'%Y-%m-%d %H:%M:%S' -d "$started")
fi
local cpu_time=$(ps -otime= -p $pid | cf_trim)
echo "started from: $started, elapsed: $elapsed, cumulative cpu time: $cpu_time"
} function cf_ps_zombies() {
ps -opid,state,command -e | awk 'NR==1 || $2=="Z"'
} function cf_connection_topology() {
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return /usr/sbin/lsof -Pan -iTCP -p $pid > /tmp/.$pid.lsof
grep -o "[0-9.:]*->[0-9.:]*" /tmp/.$pid.lsof > /tmp/.$pid.conns
grep "LISTEN" /tmp/.$pid.lsof | awk '$9~/*/{print substr($9,3)}' > /tmp/.$pid.ports echo "-------------- downstream -------------"
for port in $(cat /tmp/.$pid.ports); do
cf_connection_list_by_port $port | awk '$6=="ESTABLISHED" {print $5}' | cut -d':' -f1 | sort | uniq -c | awk '{print $2"-->localhost:"'$port'" ("$1")"}'
done echo "-------------- upstream ---------------"
local portsExpr=$(cat /tmp/.$pid.ports | sed -e 's/^/:/' -e 's/$/->/' | xargs | sed 's/ /|/g')
grep -Ev "$portsExpr" /tmp/.$pid.conns > /tmp/.$pid.out
awk -F'->' '{print $2}' /tmp/.$pid.out | sort | uniq -c | sort -nrk1 | awk '{print "localhost-->"$2" ("$1")"}'
rm -f /tmp/.$pid.lsof /tmp/.$pid.conns /tmp/.$pid.ports
} function cf_connection_list_by_pid() {
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
/usr/sbin/lsof -Pan -iTCP -p $pid
} function cf_connection_list_by_port() {
local port=$
netstat -ant| awk '$4~/[:.]'"$port"'$/'
} function cf_connection_stat_by_pid() {
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
local interval=${:-}
/usr/sbin/lsof -Pan -iTCP -p $pid -r $interval
} function cf_connection_stat_by_port() {
local port=$
netstat -ant -c| awk '$1=="Proto"{print "\n"$0};$4~/[:.]'"$port"'$/'
} function cf_listening_sockets() {
#lsof -Pnl -i4TCP -sTCP:LISTEN #low version unsupported -sTCP params
if cf_is_linux >/dev/null || cf_is_darwin >/dev/null; then
if cf_has_sudo_privilege; then
sudo /usr/sbin/lsof -Pnl -i4TCP | grep LISTEN
else
/usr/sbin/lsof -Pnl -i4TCP | grep LISTEN
fi
else
netstat -plnt >/dev/null | grep -v tcp6
fi
} function cf_traffic_by_eth() {
local eth=${:-"eth0"}
if cf_is_linux >/dev/null; then
[ ! -d /sys/class/net/$eth ] && echo "network interface not exists." && return
while true; do
local r1=`cat /sys/class/net/$eth/statistics/rx_bytes`
local t1=`cat /sys/class/net/$eth/statistics/tx_bytes`
sleep
local r2=`cat /sys/class/net/$eth/statistics/rx_bytes`
local t2=`cat /sys/class/net/$eth/statistics/tx_bytes`
local rkbps=`cf_calc "( $r2 - $r1 ) / 1024"`
local tkbps=`cf_calc "( $t2 - $t1 ) / 1024"`
echo "$eth: RX $rkbps kB/s TX $tkbps kB/s"
done
elif cf_is_darwin >/dev/null; then
# `netstat -I eth0 -w ` or `nettop -n -m tcp`
declare -a tuple
local _i1=
cf_is_zsh >/dev/null && _i1=
local _i2=
cf_is_zsh >/dev/null && _i1=
while true; do
tuple=( $(netstat -nbi -I $eth | tail - | awk '{print $7,$10}') )
local r1=${tuple[$_i1]}
local t1=${tuple[$_i2]}
sleep
tuple=( $(netstat -nbi -I $eth | tail - | awk '{print $7,$10}') )
local r2=${tuple[$_i1]}
local t2=${tuple[$_i2]}
local rkbps=`cf_calc "( $r2 - $r1 ) / 1024"`
local tkbps=`cf_calc "( $t2 - $t1 ) / 1024"`
echo "$eth: RX $rkbps kB/s TX $tkbps kB/s"
done
else
echo "unsupported os" && return
fi
} function cf_traffic_by_pid() {
! cf_is_linux >/dev/null && echo "only works in linux" && return
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return # kernel 2.6. not support, must 2.6. or later?
local pf="/proc/$pid/net/netstat"
[ ! -f $pf ] && echo "$pf not found!" && return declare -a tuple
local _i1=
cf_is_zsh >/dev/null && _i1=
local _i2=
cf_is_zsh >/dev/null && _i1=
local pname="$(cf_ps_name $pid)"
while true; do
tuple=( $(grep "IpExt: " $pf | awk 'NR==2{print $8,$9}') )
local r1=${tuple[$_i1]}
local t1=${tuple[$_i2]}
sleep
tuple=( $(grep "IpExt: " $pf | awk 'NR==2{print $8,$9}') )
local r2=${tuple[$_i1]}
local t2=${tuple[$_i2]}
local rkbps=`cf_calc "( $r2 - $r1 ) / 1024"`
local tkbps=`cf_calc "( $t2 - $t1 ) / 1024"`
echo "$pname: IN $rkbps kB/s OUT $tkbps kB/s"
done
} function cf_iotop() {
sudo iotop -bod1
} function cf_check_sum() {
local dir=${:-$PWD}
local dirsum=
for sum in $(find ${dir} -type f -print0 | xargs - cksum | awk '{print $1}')
do
dirsum=$(( ${sum} + ${dirsum} ))
done
echo ${dirsum}
} function cf_java_classpath_check() {
[ $# -eq ] && echo "please enter classpath dir" && return
[ ! -d "$1" ] && echo "not a directory" && return local tmpfile="/tmp/.cp$(date +%s)"
local tmphash="/tmp/.hash$(date +%s)"
local verbose="/tmp/cp-verbose.log" if cf_is_zsh >/dev/null;then
local -a files
local begin=
elif cf_is_bash >/dev/null;then
declare -a files
local begin=
else
echo "unsupported shell" && return
fi
files=(`find "$1" -name "*.jar"`) for f in $files; do
jarName=`basename $f`
list=`unzip -l $f | awk -v fn=$jarName '/\.class$/{print $NF,fn}'`
size=`echo "$list" | wc -l`
echo $jarName $size >> $tmphash
echo "$list"
done | sort | awk 'NF{ a[$1]++;m[$1]=m[$1]","$2}END{for(i in a) if(a[i] > 1) print i,substr(m[i],2)}' > $tmpfile awk '{print $2}' $tmpfile | awk -F',' '{i=1;for(;i<=NF;i++) for(j=i+1;j<=NF;j++) print $i,$j}' | sort | uniq -c | sort -nrk1 |
while read line; do
local dup=${line%% *}
local jars=${line#* }
local jar1=${jars% *}
local jar2=${jars#* }
local len_jar1=`grep -F "$jar1" $tmphash | grep ^"$jar1" | awk '{print $2}'`
local len_jar2=`grep -F "$jar2" $tmphash | grep ^"$jar2" | awk '{print $2}'`
local len=$(($len_jar1 > $len_jar2 ? $len_jar1 : $len_jar2))
local per=$(echo "scale=2; $dup/$len" | bc -l)
echo ${per/./} $dup $jar1 $jar2
done | sort -nr -k1 -k2 | awk 'NR==1{print "Similarity DuplicateClasses File1 File2"}{print "%"$0}'| column -t sort $tmpfile | awk '{print $1,"\n\t\t",$2}' > $verbose
echo "See $verbose for more details." rm -f $tmpfile
rm -f $tmphash
} function cf_java_class_find() {
local libdir=$
local name=$
local glob=$(cf_is_glob_enabled)
[ $glob = "false" ] && cf_enable_glob
builtin pushd $libdir >/dev/null
for j in *.jar; do
unzip -l $j | grep $name && echo $j;
done
builtin popd >/dev/null
[ $glob = "false" ] && cf_disable_glob
} function cf_java_pids() {
ps x | grep "jav[a]" | awk '{print $1}'
} function cf_java_infos() {
for p in `cf_java_pids`; do
echo "java pid: $p"
info=`ps -opid=,command= -p $p | tr ' ' '\n' | awk '/-classpath|-cp/{getline;next};/-Xmx|-Dcatalina.base/{print};/^-/{next};1' | xargs`
echo " $info"
time=`cf_ps_time $p`
echo " $time"
done
} function cf_java_threads() {
local pid=$
local vm_threads="GC task|VM |CompilerThread|Finalizer|Reference Handler|Signal Dispatcher"
"$JAVA_HOME"/bin/jstack $pid | grep "^\"" | grep -Ev "$vm_threads"
} function cf_java_sysprops() {
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
"$JAVA_HOME"/bin/jinfo -sysprops $pid
} function cf_jstack_series() {
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
local count=${:-} # defaults times
local delay=${:-0.5} # defaults 0.5 seconds local logdir=${LOG_DIR:-"/tmp"}
while [ $count -gt ]; do
if cf_is_gnu_date >/dev/null; then
local suffix=$(date +%H%M%S.%N)
else
local suffix=$(date +%H%M%S)"."$count
fi
"$JAVA_HOME"/bin/jstack $pid > $logdir/jstack.$pid.$suffix
sleep $delay
let count--
echo -n "."
done
} function cf_dmesg() {
! cf_is_linux >/dev/null && echo "only works in linux" && return dmesg -T "$@" >/dev/null
[ $? -eq ] && return dmesg "$@" | perl -w -e 'use strict;
my ($uptime) = do { local @ARGV="/proc/uptime";<>}; ($uptime) = ($uptime =~ /^(\d+)\./);
foreach my $line (<>) {
printf( ($line=~/^\[\s*(\d+)\.\d+\](.+)/) ? ( "[%s]%s\n", scalar localtime(time - $uptime + $), $ ) : $line )
}'
} function cf_trace_http_request() {
! cf_is_linux >/dev/null && echo "only works in linux" && return
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
strace -e read -s -qftp $pid >& | grep " HTTP/1[.][01][\]r[\]n"
} function cf_trace_http_response() {
! cf_is_linux >/dev/null && echo "only works in linux" && return
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
strace -e write -s -qftp $pid >& | grep "HTTP/1[.][01] "
} function cf_trace_http_req_header() {
! cf_is_linux >/dev/null && echo "only works in linux" && return
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
strace -e read -s -qftp $pid >& | grep " HTTP/1[.][01][\]r[\]n" | sed 's/\\r\\n/\n/g'
} function cf_trace_http_resp_header() {
! cf_is_linux >/dev/null && echo "only works in linux" && return
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
strace -e write -s -qftp $pid >& | grep "HTTP/1[.][01] " | sed 's/\\r\\n/\n/g'
} function cf_trace_http_invoke() {
! cf_is_linux >/dev/null && echo "only works in linux" && return
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
strace -e sendto -s -qftp $pid >& | grep " HTTP/1[.][01][\]r[\]n"
} function cf_trace_connect() {
! cf_is_linux >/dev/null && echo "only works in linux" && return
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
strace -e connect -s -qftp $pid >& | grep "port"
} function cf_trace_socket() {
! cf_is_linux >/dev/null && echo "only works in linux" && return
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
strace -e connect,socket,close -s -qftp $pid >& | grep "port"
} function cf_trace_sql_select() {
! cf_is_linux >/dev/null && echo "only works in linux" && return
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
strace -e sendto,write -s -qftp $pid >& | grep -i "[\]3select"
} function cf_trace_sql_update() {
! cf_is_linux >/dev/null && echo "only works in linux" && return
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
strace -e sendto,write -s -qftp $pid >& | grep -i "[\]3update"
} function cf_trace_sql_insert() {
! cf_is_linux >/dev/null && echo "only works in linux" && return
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
strace -e sendto,write -s -qftp $pid >& | grep -i "[\]3insert"
} function cf_trace_redis_command() {
! cf_is_linux >/dev/null && echo "only works in linux" && return
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
local cmd=$
strace -e sendto,write -s -qftp $pid >& | grep -i "$cmd[\]r[\]n"
} function cf_trace_dubbo_request() {
! cf_is_linux >/dev/null && echo "only works in linux" && return
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
strace -e read -s -qftp $pid >& | grep -i "[\]tinterface"
} function cf_trace_dubbo_invoke() {
! cf_is_linux >/dev/null && echo "only works in linux" && return
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
strace -e write -s -qftp $pid >& | grep -i "[\]tinterface"
} function cf_trace_system_call() {
! cf_is_linux >/dev/null && echo "only works in linux" && return
local pid=$
! cf_is_pid_exists >/dev/null $pid && echo "pid:$pid not exists" && return
local time=${:-} local outfile="/tmp/.sys-call.$pid"
strace -cqftp $pid -o $outfile &
local spid=$!
while [ $time -gt ]; do
sleep
let time--
echo -n "."
done
echo ""
kill $spid && echo "ok"
# if strace process still exists
cf_is_pid_exists $spid >/dev/null >& && kill - $spid
cat $outfile && rm -f $outfile
} function cf_random_entropy_stat() {
! cf_is_linux >/dev/null && echo "only works in linux" && return
while true; do
echo "entropy available:" `cat /proc/sys/kernel/random/entropy_avail`
sleep
done
} function cf_json_fmt() {
python -mjson.tool
} function cf_http_server() {
local port=${:-}
python -mSimpleHTTPServer $port >/dev/null
}

一些方便系统诊断的bash函数的更多相关文章

  1. Bash函数

    一.什么是Bash函数 Bash不支持goto语句,可以用function实现程序流程跳转.当前shell中一组组织在一起并被命名的命令.比脚本的效率高,一旦定义,就成为shell内存的一部分,可以随 ...

  2. bash函数定义/使用/传参…

    函数:function, 功能     过程式编程,代码重用         模块化编程         简洁             语法:         function f_name {    ...

  3. Bash函数使用

    #!/bin/bash function Fun_Name() { #function here echo "this is a function" } Fun_Name

  4. Bash脚本编程学习笔记08:函数

    官方资料:Shell Functions (Bash Reference Manual) 简介 正如我们在<Bash脚本编程学习笔记06:条件结构体>中最后所说的,我们应该把一些可能反复执 ...

  5. CVE: 2014-6271、CVE: 2014-7169 Bash Specially-crafted Environment Variables Code Injection Vulnerability Analysis

    目录 . 漏洞的起因 . 漏洞原理分析 . 漏洞的影响范围 . 漏洞的利用场景 . 漏洞的POC.测试方法 . 漏洞的修复Patch情况 . 如何避免此类漏洞继续出现 1. 漏洞的起因 为了理解这个漏 ...

  6. 脚本命令高级Bash脚本编程指南(31):数学计算命令

    题记:写这篇博客要主是加深自己对脚本命令的认识和总结实现算法时的一些验经和训教,如果有错误请指出,万分感谢. 高等Bash脚本编程指南(31):数学盘算命令 成于坚持,败于止步 操作数字 factor ...

  7. 【转】Linux 技巧: Bash 参数和参数扩展

    重点看下清单7 现在,很多 Linux® 和 UNIX® 系统上都有 bash shell,它是 Linux 上常见的默认 shell.通过本文,您将了解到如何在 bash 脚本中处理参数和选项,以及 ...

  8. bash编程总结

    bash应该是目前Linux上最流行的shell脚本解释程序了(还有个shell叫dash,我太讨厌这个东东了.),只要你在linux上工作,并且希望自己能够工作得更愉悦,那么你应该熟悉最基本的bas ...

  9. Shell 函数定义与调用

    linux shell 可以用户定义函数,然后在 shell 脚本中可以随便调用. 以一个计算两数之和的函数为例: #! /bin/bash # 函数定义 sum(){ return $(($1+$2 ...

随机推荐

  1. 如何将excel 数据库表结构生成powerdesign物理模型

    Option Explicit Dim mdl ' the current model Set mdl = ActiveModel If (mdl Is Nothing) Then MsgBox &q ...

  2. bootstrap-3-fileinput上传案例

    效果 导入的js和css <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/ ...

  3. HTTPS IP直连问题小结

    HTTPS IP直连问题小结: https://blog.csdn.net/leelit/article/details/77829196 可以使用OkHttpClient进行相同IP地址,不同DNS ...

  4. PhpStorm配置SVN的完整方法

    1.安装SVN时注意选择“command line client tools"默认是不安装的 2.设置系统环境变量 3.在PhpStorm上设置如下 4.然后通过VCS就可以上传导入你的工程 ...

  5. 【一步步学OpenGL 20】 -《点光源》

    教程 20 点光源 原文: http://ogldev.atspace.co.uk/www/tutorial20/tutorial20.html CSDN完整版专栏: http://blog.csdn ...

  6. 如何永久激活(破解) IntelliJ IDEA 2018.2

    1.去官网下载并安装 idea 地址:https://www.jetbrains.com/idea/download 文件有点大,耐心等待一会儿. 2.下载破解(crack) jar 包 地址 htt ...

  7. C#之值类型和引用类型

    本文意在巩固基础知识,并不是对其进行深入剖析,还望理解.本文是对此项知识的整理文,有些内容来源于网络,其他为博主原创,所以难免会有一些小得瑕疵,敬请谅解.所有示例均是博主测试过的,如有转载请标明出处, ...

  8. Navicat Win 和 Mac 视图类快捷键对比

    Navicat 查询是根据用户需求从数据库提取可读格式的数据,Navicat 提供两个强大的工具与 SQL 查询工作:查询创建工具和查询编辑器,查询创建工具可视觉化地创建查询,查询编辑器可直接编辑查询 ...

  9. Swift Enum 枚举

    前言 枚举是一种自定义的数据类型,在 Swift 中枚举类型拥有相当高的自由度.在 Swift 语言中枚举是一级类型,它拥有在其他语言中只有类才拥有的一些特性,比如实例方法,实例构造器等. 枚举声明的 ...

  10. 分析轮子(四)- 我也玩一把 Serializable.java

    前言:在写 分析轮子(一)-ArrayList.java 的时候曾经下过一个结论 “实现Serializable接口,表示ArrayList是可序列化的”,这个结论是以往学习的经验所得,并且平时在编程 ...