微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

shell 练习题【1】

:@[toc]

图形化 Shell 编程

1. 编写 hello world 脚本

#!/bin/sh

echo "Hello, World!"

2. 查找可执行文件

当你从命令行中运行一个程序的时候,Linux 系统会搜索一系列目录来查找对应的文件。这些目录被定义在环境变量 PATH 中。如果你想找出系统中有哪些可执行文件可供使用,只需要扫描 PATH 环境变量中所有的目录就行了。

jiaming@jiaming-VirtualBox:~/Documents/shellScript$ bash findExe.sh > /tmp/findExeOutput.txt | head -n 10 /tmp/findExeOutput.txt
/usr/local/sbin:
/usr/local/bin:
/usr/sbin:
  /usr/sbin/aa-remove-unkNown
  /usr/sbin/aa-status
  /usr/sbin/accept
  /usr/sbin/accessdb
  /usr/sbin/acpid
  /usr/sbin/addgnupghome
  /usr/sbin/addgroup
jiaming@jiaming-VirtualBox:~/Documents/shellScript$ cat findExe.sh 
#!/bin/bash
# 
IFS=:
for folder in $PATH
do
    echo "$folder:"
    for file in $folder/*
    do
        if [ -x $file ]; then
            echo "  $file"
        fi
    done
done

3. 创建多个用户账户

将需要添加新用户账户放在一个文本文件中,然后创建一个简单的脚本进行处理。

jiaming@jiaming-VirtualBox:~/Documents/shellScript$ sudo bash useradd.sh 
adding rich
adding christine
adding barbara
adding tim
jiaming@jiaming-VirtualBox:~/Documents/shellScript$ cat useradd.sh 
#!/bin/bash
# 
input="users.csv"
while IFS=',' read -r userid name
do
    echo "adding $userid"
    useradd -c "$name" -m $userid
done < "$input"
jiaming@jiaming-VirtualBox:~/Documents/shellScript$ cat users.csv 
rich,Richard Blum
christine,Christine Bresnahan
barbara,Barbara Blum
tim,Timothy Bresnahan

4. 备份日志

每周 5 使用 tar 命令 备份 /var/log 下的所有日志文件

  • tar 命令
  • crontab
  • 压缩:tar -zcvf [filename].tar.gz [filename/directory] # z:压缩选项
  • 解压:tar -zxvf [filename].tar.gz
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user	command
17 *	* * *	root    cd / && run-parts --report /etc/cron.hourly
25 6	* * *	root	test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6	* * 7	root	test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6	1 * *	root	test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
# minute hour day month week command cmd
  • 星号:代表所有可能的值;
  • 逗号:用逗号隔开的值指定一个列表范围, 1,2,5,7,8,9
  • 中杠:表示一个整数范围,2-6表示2,3,4,5,6
  • 正斜线:指定时间的间隔频率,0-23/2每两小时执行一次;

在这里插入图片描述

在这里插入图片描述

5. 安装必要的库

满血复活你的 Ubuntu

6. 监控内存和磁盘容量,小于给定值报警

mail 用法有问题。

#!/bin/bash

disk_size=$(df / | awk '/\//{print $4}')

mem_size=$(free | awk '/Mem/{print $4}')

while :
do
	if [ $disk_size -le 512000 -a $mem_size -le 1024000 ]
	then
		mail -s "Warning" jiaming << EOF
	Insufficient resources
EOF
	fi
done

7. shell 函数

# 第 1 种

#!/bin/bash
func1() {
        :
}
function func2 {
        echo -n "func2's result:"
        echo $[ $1 + $2 ]
}
result=$(func2 $1 $2)
echo $result
#func2's result:3

# 第 2 种

#!/bin/bash
func1() {
        :
}
function func2 {
        echo -n "func2's result:"
        echo $[ $1 + $2 ]
}

func2 $1 $2
#func2's result:3

# 第 3 种

#!/bin/bash
function func {
	read -p "Enter a value: " value
	echo $[ $value * 2]
}
result=$(func)
echo "The new value is $result"

#Enter a value: 200
#The new value is 400
#read 中的输出信息并不会作为 STDOUT 在 echo 中输出

返回值

函数运行完毕后,在结束时会返回一个退出状态码。

  1. 退出状态码。使用$?查看,只会判断函数最后一条命令是否正常运行。
  2. return。能够返回特定的状态码,通过$?查看。
  3. 使用函数输出。即将函数保存到一个变量中,如上面第 3 种形式。

8. 猜数字小游戏

#!/bin/bash

num=$[RANDOM%100+1]
echo "$num"

while :
do
	read -p "guess a number between 1 to 100: " number
	if [ $number -eq $num ]
	then
		echo "Bingo"
		exit
	elif [ $number -gt $num ]
	then
		echo "too more."
	else
		echo "too smaller."
	fi
done

9. 根据用户类型安装 vsftpd(字符串)

检测本机当前用户是否为超级管理员,如果是管理员,则使用 yum 安装 vsftpd,如果不是,则提示退出

#!/bin/bash

if [ $USER == "root" ]
then
	yum -y install vsftpd
else
	echo "permission denied."
fi

10. 根据用户类型安装 vsftpd(UID)

检测本机当前用户是否为超级管理员,如果是管理员,则使用 yum 安装 vsftpd,如果不是,则提示退出

#!/bin/bash

if [ $UID -eq 0 ];then
	yum -y install vsftpd
else
	echo "permission denied."
fi

11. 创建用户名以及密码

提⽰⽤⼾输⼊⽤⼾名和密码,脚本⾃动创建相应的账⼾及配置密码。 如果⽤⼾不输⼊账⼾名,则提⽰必须输⼊账⼾名并退出脚本;如果⽤⼾不输⼊密码,则统⼀使⽤认的 123456 作为密码

#!/bin/bash

read -p "enter user name: " user
if [ -z $user ]; then
	echo "must enter a name"
	exit 2
fi

stty -echo
read -p "enter passwd: " passwd
stty echo

passwd=${pass:-123456} 
useradd "$user"
echo "$user:$passwd" | chpasswd # Ubuntu 解决方
# 赋予初值写法
jiaming@jiaming-VirtualBox:~/Documents$ a=${b:-1}
jiaming@jiaming-VirtualBox:~/Documents$ echo $a
1
jiaming@jiaming-VirtualBox:~/Documents$ echo $b

jiaming@jiaming-VirtualBox:~/Documents$ 

12. 输入三个数升序排列

#!/bin/bash

read -p "enter a num: " num1
read -p "enter a num: " num2
read -p "enter a num: " num3

tmp=0
if [ $num1 -gt $num2 ];then
	tmp=$num1
	num1=$num2
	num2=$tmp
fi

if [ $num1 -gt $num3 ];then
	tmp=$num1
	num1=$num3
	num3=$tmp
fi

if [ $num2 -gt $num3 ];then
	tmp=$num2
	num2=$num3
	num3=$tmp
fi

echo $num1 $num2 $num3

13. 剪刀石头布

#!/bin/bash
game=(stone scissor fabric)
num=$[RANDOM%3]
computer=${game[$num]}

echo "$computer"

echo "1. Stone"
echo "2. Scissor"
echo "3. Fabric"

read -p "enter 1-3: " person
case $person in
	1)
		if [ $num -eq 0 ]
		then
			echo "Deuce."
		elif [ $num -eq 1 ]
		then
			echo "You win."
		else
			echo "You lose."
		fi ;;
	2)
		if [ $num -eq 0 ]
		then
			echo "You lose."
		elif [ $num -eq 1 ]
		then
			echo "Deuce."
		else
			echo "You Win"
		fi ;;
	3)
		if [ $num -eq 0 ]
		then
			echo "You Win."
		elif [ $num -eq 1 ]
		then
			echo "You lose."
		else
			echo "Deuce"
		fi ;;
	*)
		echo "must enter a number between 1-3"
esac

14. 编写脚本测试 192.168.4.0/24 整个网段中哪些主机处于开机状态,哪些主机处于关机状态(for 版本)

#!/bin/bash

for i in {1..254}
do
	# 每隔0.3妙ping一次,一共ping2次,并以1毫秒为单位设置ping的超时时间
	ping -c 2 -i 0.3 -W 1 192.168.4.$i &>/dev/null
	if [ $? -eq 0 ]; then
		echo "192.168.0.$i is up"
	else
		echo "192.168.0.$i is down"
	fi
done
jiaming@jiaming-VirtualBox:~/Documents$ bash testNetHost.sh 
192.168.4.1 is up
192.168.4.2 is down
192.168.4.3 is down
192.168.4.4 is down
192.168.4.5 is down
...

15. 编写脚本测试 192.168.4.0/24 整个网段中哪些主机处于开机状态,哪些主机处于关机状态(while 版本)

#!/bin/bash

i=1
while [ $i -le 254 ]
do
	ping -c 2 -i 0.3 -W 1 192.168.4.$i &>/dev/null
	if [ $? -eq 0 ]; then
		echo "192.168.4.$i is up"
	else
		echo "192.168.4.$i is down"
	fi
done

16. 编写脚本测试 192.168.4.0/24 整个网段中哪些主机处于开机状态,哪些主机处于关机状态(多进程版本)

#!/bin/bash

function myping {
	i=1
	while [ $i -le 254 ]
	do
		ping -c 2 -i 0.3 -W 1 192.168.4.$i &>/dev/null
		if [ $? -eq 0 ]; then
			echo "192.168.4.$i is up"
		else
			echo "192.168.4.$i is down"
		fi
	done
}

for i in {1..254}
do
	myping 192.168.4.$i & # 使用 & 符合,将执行的函数放入后台执行,这样做的好处是不需要等待ping第一台主机的回应,就可以继续ping第二台主机,以此类推
done

17. 编写脚本,显示进度条

#!/bin/bash

function processbar {
	while :
	do
		echo -n "#"
		sleep 0.2
	done
}

processbar &
tar -zc -f root.tar.gz /
echo "tar done."

18. 定义一个显示进度的函数,屏幕快速显示 | / - \

#!/bin/bash 

function rotate_line {
	INTERVAL=0.5
	COUNT="0"
	while :
	do
		COUNT=`expr $COUNT + 1`
		case $COUNT in
		"1")
			echo -e '-'"\b\c"
			sleep $INTERVAL
			;;
		"2")
			echo -e '\\'"\b\c"
			sleep $INTERVAL
			;;
		"3")
			echo -e "|\b\c"
			sleep $INTERVAL
			;;
		"4")
			echo -e "/\b\c"
			sleep $INTERVAL
			;;
		*)
			COUNT="0"
			;;
		esac
done
}

rotate_line

19. 99 乘法表

#!/bin/bash 
for i in `seq 9`
do
	for j in `seq $i`
	do
		echo -n "$j*$i=$[i*j]	"
	done
	echo
done

20. Ubuntu 批量添加用户

jiaming@jiaming-VirtualBox:~/Documents$ cat users.txt 
user001:x:1001:1000::/home/wxc:/bin/bash
user002:x:1002:1002::/home/yx:/bin/bash
user003:x:1003:1003::/home/lhm:/bin/bash
user004:x:1004:1004::/home/byf:/bin/bash
user005:x:1005:1006::/home/lhb:/bin/bash
user006:x:1006:1006::/home/sj:/bin/bash
user007:x:1007:1007::/home/djy:/bin/bash
user008:x:1008:1008::/home/aoko:/bin/bash
jiaming@jiaming-VirtualBox:~/Documents$ cat users.txt 
user001:x:1001:1000::/home/wxc:/bin/bash
user002:x:1002:1002::/home/yx:/bin/bash
user003:x:1003:1003::/home/lhm:/bin/bash
user004:x:1004:1004::/home/byf:/bin/bash
user005:x:1005:1006::/home/lhb:/bin/bash
user006:x:1006:1006::/home/sj:/bin/bash
user007:x:1007:1007::/home/djy:/bin/bash
user008:x:1008:1008::/home/aoko:/bin/bash
sudo newusers < users.txt
sudo chpasswd < passwd.txt

在这里插入图片描述

21. 批量修改文件后缀名

jiaming@jiaming-VirtualBox:~/Documents/extendTypeFiles$ ls
1.doc  2.doc  3.png  changeExtendFile.sh
#!/bin/bash 

for i in `ls *.$1`
do
    mv $i ${i%.*}.$2 # ${i%.*} —— **拿掉 .以及后面的内容**
done
jiaming@jiaming-VirtualBox:~/Documents/extendTypeFiles$ sudo bash changeExtendFile.sh txt doc

22. 使用 expect 工具自动交互密码远程其他主机安装 httpd 软件(?)

#!/bin/bash 
# apt-get install expect
rm -rf ~/.ssh/kNow_hosts # 删除后,远程任何主机都会询问是否确认要连接该主机
expect <<EOF
spawn ssh 10.0.2.15
expect "yes/no" {send "yes\r"}
expect "password" {send "密码\r"} # 将密码改为自己
expect "#" {send "apt-get install httpd\r"}
expect "#" {send "exit\r"}
EOF

23. 一键部署 LNMP

#!/bin/bash 

function menu {
	clear
	echo "##############----Menu----##############"
	echo "# 1. Install Nginx"
	echo "# 2. Install MysqL"
	echo "# 3. Install PHP"
	echo "# 4. Exit Program"
	echo "########################################"
}

function choice {
	read -p "Please choice a menu[1-9]: " select
}

function install_Nginx {
	id Nginx &>/dev/null 
	if [ $? -ne 0 ];then
		useradd -s /sbin/nologin Nginx
	fi
	if [ -f Nginx-1.8.0.tar.gz ];then
		tar -xf Nginx-1.8.0.tar.gz
		cd Nginx-1.8.0
		yum -y install gcc pcre-devel openssl-devel zlib-devel zlib-devel make
		./configure --prefix=/usr/local/Nginx --with-http_ssl_module
		make
		make install 
		ln -s /usr/local/Nginx/sbin/Nginx /usr/sbin/ 
		cd ..
	else
		echo "no Nginx source code package."
	fi
}

function install_MysqL {
	yum -y install gcc gcc-c++ cmake ncurses-devel perl
	id MysqL &>/dev/null 
	if [ $? -ne 0 ];then
		useradd -s /sbin/nologin MysqL
	fi
	if [ -f mysql-5.6.25.tar.gz ];then
		tar -xf mysql-5.6.25.tar.gz
		cd mysql-5.6.25
		cmake .
		make
		make install
		/usr/local/MysqL/scripts/MysqL_install_db --user=MysqL --datadir=/usr/local/MysqL/data/ --basedir=/usr/local/MysqL/
		chown -R root.MysqL /usr/local/MysqL
		chown -R MysqL /usr/local/MysqL/data
		/bin/cp -f /usr/local/MysqL/support-files/my-default.cnf /etc/my.cnf
		echo "/usr/local/MysqL/lib/" >> /etc/ld.so.conf 
		ldconfig
		echo 'PATH=\$PATH:/usr/local/MysqL/bin/' >> /etc/profile 
		export PATH
	else
		echo "no MysqL source code package."
		exit 
	fi
}
function install_PHP {
	yum -y install gcc libxml2-devel
	if [ -f mhash-0.9.9.9.tar.gz ]:then
		tar -xf mhash-0.9.9.9
		cd mhash-0.9.9.9
		./configure
		make
		make install
		cd ..
		if [ ! -f /usr/lib/libmhash.so ];then
			ln -s /usr/local/lib/libmhash.so /usr/lib/ 
		fi
		ldconfig
	else
		echo "no mhash source code package."
		exit
	fi
	if [ -f libmcrypt-2.5.8.tar.gz ];then
		tar -xf libmcrypt-2.5.8.tar.gz
		cd libmcrypt-2.5.8
		./configure
		make
		make install
		cd ..
		if [ ! -f /usr/lib/libmcrypt.so ];then
			ln -s /usr/local/lib/libmcrypt.so /usr/lib/ 
		fi
		ldconfig
	else
		echo "no libmcrypt source code package."
		exit
	fi
	if [ -f PHP-5.4.24.tar.gz ];then
		tar -xf PHP-5.4.24.tar.gz
		cd PHP-5.4.24
		./configure --prefix=/usr/local/PHP5 --width-MysqL=/usr/MysqL --enable-fpm --enable-mbstring --with-mcrypt --with-mhash --with-config-file -path=/usr/local/PHP5/etc --with-MysqLi=/usr/local/MysqL/bin/MysqL_config
		make && make Install
		/bin/cp -f PHP.ini-production /usr/local/PHP5/etc/PHP.ini
		/bin/cp -f /usr/local/PHP5/etc/PHP-fpm.conf.default /usr/local/PHP5/etc/PHP-fpm.conf
		cd ..
	else
		echo "no PHP source code package."
		exit
	fi	
}

while :
do
	menu
	choice
	case $select in 
	1)
		install_Nginx
		;;
	2)
		install_MysqL
		;;
	3)
		install_PHP
		;;
	4)
		exit
		;;
	*)
		echo Sorry!
esac
done

24. 编写脚本快速克隆 KVM 虚拟机

#!/bin/bash 
# 编写脚本快速克隆 KVM 虚拟机

# 本脚本针对 RHEL7/2 或 Centos7.2
# 本脚本需要提前准备一个 qcow2 格式的虚拟机模板,
# 名称为 /var/lib/libvirt/images /.rh7_template 的虚拟机模板
# 该脚本使用 qemu-img 快速创建快照虚拟机
# 脚本使用 sed 修改模板虚拟机的配置文件,将虚拟机名称、UUID、磁盘文件名、MAC 地址
# exit code
# 	65 -> user input nothing
#	66 -> user input is not a number
#	67 -> user input out of range
#	68 -> vm disk image exists

IMG_DIR=/var/lib/libvirt/images
BASEVM=rh7_template

read -p "Enter VM number: " VMNUM
if [ $VMNUM -le 9 ];then
	VMNUM=0$VMNUM
fi

if [ -z "${VMNUM}" ];then
	echo "You must input a number."
	exit 65
elif [[ ${VMNUM} =~ [a-z] ];then
	echo "You must input a number."
	exit 66
elif [ ${VMNUM} -lt 1 -o ${VMNUM} -gt 99 ];then
	echo "Input out of range"
	exit 67
fi

NEWVM=rh7_node${VMNUM}

if [ -e $IMG_DIR/${NEWVM}.img ];then
	echo "File exists."
	exit 68
fi

echo -en "Creating Virtual Machine disk image...\t"
qemu-img create -f qcow2 -b $IMG_DIT/.${BASEVM}.img $IMG_DIR/${NEWVM}.img &> /dev/null 

echo -e "\e[32;1m[OK]\e[0m"

# virsh dumpxml ${BASEVM} > /tmp/myvm.xml
cat /var/lib/libvirt/images/.rhe17.xml > /tmp/myvm.xml
sed -i "/<name>${BASEVM}/s/${BASEVM}/${NEWVM}/" /tmp/myvm.xml
sed -i "/uuid/s/<uuid>.*<\/uuid>/<uuid>$(uuidgen)<\/uuid>/" /tmp/myvm.xml
sed -i "/${BASEVM}\.img/s/${BASEVM}/${NEWVM}/" /tmp/myvm.xml

# 修改 MAC 地址,本例使用的是常量,每位使用该脚本的用户需要根据实际情况修改这些值
sed -i "/mac /s/a1/0c/" /tmp/myvm.xml

echo -en "Defining new virtual machine....\t\t"
virsh define /tmp/myvm.xml &> /dev/null 
echo -e "\e[32;1m[OK]\e[0m"

25. 点名器脚本

#!/bin/bash 
while :
do
	line=`cat students.txt | wc -l`
	num=$[RANDOM%line+1]
	sed -n "${num}p" students.txt
	sleep 0.2
	clear
done

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐