Shell实战之变量的高级用法

#!/usr/bin/env bash
#字符串处理完整脚本

string="Bigdata process framework is Hadoop,Hadoop is an open source project"

function tips_info
{
	echo "******************************************"
	echo "***  (1) 打印string长度"
	echo "***  (2) 在整个字符串中删除Hadoop"
	echo "***  (3) 替换第一个Hadoop为Mapreduce"
	echo "***  (4) 替换全部Hadoop为Mapreduce"
	echo "******************************************"
}

function print_len
{
	if [ -z "$string" ];then
		echo "Error,string is null"
		exit 1
	else
		echo "${#string}"
	fi
}

function del_hadoop
{
	if [ -z "$string" ];then
		echo "Error,string is null"
		exit 1
	else
		echo "${string//Hadoop/}"
	fi
}

function rep_hadoop_mapreduce_first
{
	if [ -z "$string" ];then
		echo "Error,string is null"
		exit 1
	else
		echo "${string/Hadoop/Mapreduce}"
	fi
}

function rep_hadoop_mapreduce_all
{
        if [ -z "$string" ];then
                echo "Error,string is null"
                exit 1
        else
                echo "${string//Hadoop/Mapreduce}"
        fi
}


while true
do
    echo "【string=\"$string\"】"
    tips_info
    read -p "Please Switch a Choice: " choice
    case "$choice" in
    	1)
    		echo
    		echo "Length Of String is: `print_len`"
    		echo
    		continue
    		;;
    	2)
    		echo
    		echo "删除Hadoop后的字符串为:`del_hadoop`"
    		echo
    		;;
    	3)
    		echo 
    		echo "替换第一个Hadoop的字符串为:`rep_hadoop_mapreduce_first`"
    		echo
    		;;
    	4)
    		echo 
                    echo "替换第一个Hadoop的字符串为:`rep_hadoop_mapreduce_all`"
                    echo
    		;;
    	q|Q)
    		exit 0
    		;;
    	*)
    		echo "error,unlegal input,legal input only in { 1|2|3|4|q|Q }"
    		continue	
    		;;
    esac
done
复制代码

#!/bin/bash
#获取系统的所有用户并输出

index=1

for user in `cat /etc/passwd | cut -d ":" -f 1`
do
	echo "This is $index user: $user"
	index=$(($index + 1))
done
复制代码

#!/bin/bash
#根据系统时间计算今年或明年

echo "This year have passed $(date +%j) days"
echo "This year have passed $(($(date +%j)/7)) weeks"

echo "There is $((365 - $(date +%j))) days before new year"
echo "There is $(((365 - $(date +%j))/7)) weeks before new year"
复制代码

#!/bin/bash
#监控nginx

nginx_process_num=$(ps -ef | grep nginx | grep -v grep | wc -l)

if [ $nginx_process_num -eq 0 ];then
	systemctl start nginx
fi
复制代码

#!/bin/bash
#求和

while true
do
	read -p "pls input a positive number: " num

    #判断是不是整数
	expr $num + 1 &> /dev/null

	if [ $? -eq 0 ];then
	    #判断是不是正整数
		if [ `expr $num \> 0` -eq 1 ];then
			for((i=1;i<=$num;i++))
			do
				sum=`expr $sum + $i`
			done	
			echo "1+2+3+....+$num = $sum"
			exit
		fi
	fi
	echo "error,input enlegal"
	continue
done
复制代码
#!/bin/bash
#利用bc浮点数运算

read -p "num1: " num1
read -p "num2: " num2

num3=`echo "scale=4;$num1/$num2" | bc`

echo "$num1 / $num2 = $num3"
复制代码

你可能感兴趣的:(Shell实战之变量的高级用法)