习题1:打印99乘法表
#!/bin/bash
#
for ((j=1;j<=9;j++))
do
for ((i=1;i<=j;i++))
do
echo -e -n "${i}x${j}=$[${i}*${j}]\t"
done
echo
done
习题2:写一个脚本
(1)创建目录/tmp/dir-当前日期时间;例如/tmp/dir-20150707-155503。
(2)在此目录中创建10个空文件,分别为file1-file10;
#!/bin/bash
basedir=/tmp/dir-`date +%Y%m%d-%H%M%S`
mkdir -p $basedir
for d in {1..10}
do
touch $basedir/file$d
done
习题3:写一个脚本
(1)创建用户tuser1-tuser9;
(2)创建目录/tmp/dir-当前日期;
(3)在/tmp/dir-当前日期 目录中创建9个空文件file101-file109
(4)将file101的属主改为tuser1,依次类推,一直将file109的属主改为tuser9;
#!/bin/bash
basedir=/tmp/dir-`date +%Y%m%d`
mkdir -p $basedir
for d in {1..9} ;do
filename=$basedir/file10$d
touch $filename
useradd tuser$d
chown tuser$d $filename
done
习题4:写一个脚本,完成以下任务。
(1)添加5个用户,user1-user5,每个用户的密码同用户名
(2)添加密码完成后不显示passwd执行结果
(3)显示添加成功信息
#!/bin/bash
for i in `seq 5`
do
username=user${i}
useradd $username
echo $username | passwd --stdin $username &> /dev/null
echo "$username created successfully"
done
习题5:写一个脚本
(1)脚本可以接受一个以上的文件路径作为参数;
(2)显示每个文件所拥的行数;
#!/bin/bash
for file in $*
do
lines=`wc -l $file | cut -d' ' -f1`
echo "$file has $lines lines."
done
习题6:写一个脚本,不使用awk
显示/etc/passwd文件中位于文件的第偶数行的用户名;并显示共有多少个这样的用户
#!/bin/bash
totalUsers=`wc -l /etc/passwd | cut -d' ' -f1`
for i in `seq 2 2 $totalUsers`; do
userName=`head -n $i /etc/passwd | tail -1 | cut -d: -f1`
echo $userName
echo $userName >> /tmp/count.tmp
done
echo "Total users: `wc -l /tmp/count.tmp | cut -d' ' -f1` ."
习题7:指定一个用户名,判断此用户的用户名和它的基本组的组名是否相同
#!/bin/bash
if [ $# -ne 1 ] ;then
echo "agrs error"
exit 3
fi
if ! id $1 &>/dev/null ;then
echo "$1 Not Exsits"
exit 4
fi
username=$1
groupname=`id $username -gn`
if [ "$username" == "$groupname" ]
then
echo "Same."
else
echo "Not same."
fi
习题8:判断当前主机的CPU生产商,(其信息保存在/proc/cpuinfo文件中)
如果是:AuthemticAMD,就显示其为AMD公司
如果是:GenuineIntel,就显示其为 Intel公司
否则,就显示其为其他公司。
#!/bin/bash
CPU=`egrep "^vendor_id" /proc/cpuinfo | tail -1 | cut -d: -f2`
if [ $CPU == 'GenuineIntel' ] ;then
echo "Intel"
elif [ $CPU == 'AuthemticAMD' ] ;then
echo "AMD"
else
echo "Other"
fi
习题9:给定三个用户名,将这些用户的帐号信息提取出来,然后放入/tmp/test.txt文件中,并在行首给定行号。
#!/bin/bash
if [ $# -ne 3 ] ;then
echo "agrs error"
exit 3
fi
i=0
for user in $*
do
let i++
echo -e "$i\t`grep "^$user:" /etc/passwd`" >> /tmp/test.txt
done
习题10:依次向/etc/passwd中的每个用户问好:hello 用户名,并显示用户的shell
例如:Hello ,root ,your shell :/bin/bash。
#!/bin/bash
#
awk -F':' '{print "hello,",$1," your shell :",$7}' /etc/passwd
习题11:计算100以内所有能被3整除的整数的和
#!/bin/bash
#
SUM=0
for i in `seq 3 3 100`
do
let SUM+=$i
done
echo "sum: $SUM"
习题12:查询当前192.168.1.x网段内,那些IP被使用了,输出这些IP到一个文件中。
#!/bin/bash
#
for i in {1..254}
do
IP=192.168.1.$i
if ping -w 1 -q $IP ;then
echo $IP >> /tmp/ips.txt
fi
done
原创文章,作者:XIAJIDONG,如若转载,请注明出处:http://www.178linux.com/76714

