Shell脚本实例 gaunthan Posted on Jul 12 2016 ? ShellScript ? ## 系统管理 ### 查询线上线下主机 ```bash #!/bin/bash # updowntest.sh # note: run as root UPHOSTS=/var/log/uphosts.`date +%m%d%y` DOWNHOSTS=/var/log/downhosts.`date +%m%d%y` PREFIX=192.168.1 for OCTEL in `seq 1 254` do echo -en "Pinging ${PREFIX}.${OCTEL}..." ping -c1 -w1 ${PREFIX}.${PCTEL} > /dev/null 2>&1 if [ "$?" -eq "0" ];then echo " OK" echo "${PREFIX}.${OCTEL}" >> ${UPHOSTS} else echo " Failed" echo "${PREFIX}.${OCTEL}" >> ${DOWNHOSTS} fi done ``` ### 过滤URL以获得域名 ```bash #!/bin/bash # getdomain.sh getdomain() { url=$1 url_without_proto=${url#*://} echo "$url becomes $url_without_proto" domain_and_port=${url_without_proto%%/*} echo "$url_without_proto becomes $domain_and_port" domain=${domain_and_port%:*} echo "$domain_and_port becomes $domain" getent hosts $domain | head -1 } for url in $* do getdomain $url done ``` ## 算法实现 ### 冒泡排序 ```bash #!/bin/bash # bubblesort.sh bubblesort() { declare -a local array=( "$@" ) local n=${#array[@]} for((i=0; $i < ${n} - 1; i++)); do for((j=0; $j < ${n} - $i - 1; j++)); do nextj=`expr $j + 1` if [ "${array[$j]}" -gt "${array[$nextj]}" ]; then tmp=${array[$j]} array[$j]=${array[$nextj]} array[$nextj]=$tmp fi done done echo ${array[@]} } read -p "Input integers, seperated with bankspace: " -a array echo "array length: ${#array[@]}" echo "Prepare to sort this array: " echo ${array[@]} array=( `bubblesort ${array[@]}` ) echo "Result: " echo ${array[@]} ``` 赏 Wechat Pay Alipay Shell脚本入门知识 Linux 配置无线网卡