Linux Shell经典面试题(其一)
参考:http://blog.csdn.net/hiyun9/article/details/52057255
1.使用for循环在/oldboy目录下通过随机小写10个字母加固定字符串oldboy批量创建10个html文件,名称例如为:
[root@oldboy oldboy]# sh /server/scripts/oldboy.sh
[root@oldboy oldboy]# ls
coaolvajcq_oldboy.html qnvuxvicni_oldboy.html vioesjmcbu_oldboy.html
gmkhrancxh_oldboy.html tmdjormaxr_oldboy.html wzewnojiwe_oldboy.html
jdxexendbe_oldboy.html ugaywanjlm_oldboy.html xzzruhdzda_oldboy.html
qcawgsrtkp_oldboy.html vfrphtqjpc_oldboy.html
############批量创建html文件脚本编写##############
$ vim create-oldboy-html.sh
#!/bin/sh
WORK_DIR=/oldboy
create(){
i=1
while ($i<11)
do
cd $WORK_DIR && touch `</dev/urandom tr -dc "a-z" | head -c 10`_oldboy.html
i = $($i+1)
done
}
check(){
if [ ! -d $WORK_DIR ]; then
mkdir $WORK_DIR
create
else
create
fi
}
check
// 将上述文件名中的oldboy全部改成oldgirl(用for循环实现),并且html改成大写【至少两种方法实现】
############批量修改html文件名脚本编写,方法一##############
$ vim edit-oldgirl-HTML-1.sh
#!/bin/bash
change_name(){
DIR=/oldboy
FILE=`ls /oldboy`
GIRL=_oldgirl.HTML
for i in $FILE
do
c=`echo $i | cut -c 1-10`
mv $DIR/$c* $DIR/$c$GIRL
done
}
change_name
############批量修改html文件名脚本编写,方法二##############
$ vim edit-oldgirl-HTML-2.sh
#!/bin/bash
change_name(){
DIR=/oldboy
FILE=`ls /oldboy`
GIRL=_oldgirl.HTML
for i in $FILE
do
c=`echo $i | awk -F '_' '{print $1}'`
mv $DIR/$c* $DIR/$c$GIRL
done
}
change_name
2.批量创建10个系统账号oldboy01-oldboy10并设置密码(密码为随机8位字符串)。
######批量创建系统账号脚本编写
vim create_sys_account.sh
#!/bin/bash
USER=oldboy
create_user(){
for i in {01..10}
do
RPASSWD=$(tr -dc [:alpha:] < /dev/urandom | head -c 8)
useradd $USER$i
echo $RPASSWD | passwd $USER$i --stdin
echo $USER$i----$RPASSWD >> /oldboy/userpassword.txt
done
}
del_user(){
for j in {01..10}
do
userdel $USER$j
rm -rf /home/$USER$j
done
}
case $1 in
create)
create_user
;;
del)
del_user
;;
*)
echo "Usage:Please use $0 create or $0 del."
echo "#######################"
echo "create: create user $USER 01-10 and give it random passwd."
echo "del: delete $USER 01-10 and /home/$USER 01-10 directory."
;;
esac
[root@cjy linux-20]# ./create_sys_account.sh
Usage:Please use ./4.sh create or ./create_sys_account.sh del.
####################################
create: create user oldboy 01-10 and give it random passwd.
del: delete oldboy 01-10 and /home/oldboy 01-10 directory.
[root@cjy linux-20]# ./create_sys_account.sh create
正在创建信箱文件: 文件已存在