首先明确几个shell脚本变量:
a. $0 代表shell 脚本名称
b. $1-n 代表传入的参数 从第一个到第n个
c. $@ 代表所有参数列表
d. $* 代表所有参数列表
e. $# 代表传入参数的个数
下面学习一段代码:
echo -n “Please input a username”
read username
# 从 /etc/passwd 文件中查找含有username的行,然后送到cut提取由“:”分割的字段1,3,4字段
userinfo=`cat /etc/passwd | grep "^$username:" | cut -d ":" -f 1,3,4`
#从/etc/passwd 文件中提取由“:”分割的字段1,然后送到grep查找想要的hanyouusername的字段的行并且包含行号,然后送到cut提取行号,叼
line=`cat /etc/passwd | cut -d ":" -f 1|grep -n "^$username$"|cut -d ":" -f 1`
#接上,将passwd文件从头开始到第line行提取,送到tail提取末尾行,也就是抽出第line行,然后送到cut 提取由“:”分割的1,3,4字段
userinfo=`head -$line /etc/passwd | tail -1 | cut -d ":" -f 1,3,4`
最后解决一个实际问题:
要求:
#在主目录建立两个目录,file-dir,dir-dir
#要求输入任意路径,将该路径下的目录存放到dir-dir中,文件存放到file-dir中
filepath=$HOME/file-dir
dirpath=$HOME/dir-dir
if [ -d $filepath ]
then
echo -n "delete old file-dir now!!![yes]"
read cmd
case $cmd in
"yes"|"YES"|"Yes"|"")
rm -rf $filepath
;;
*)
exit 0
;;
ease
fi
if [ -d $dirpath ]
then
echo -n "delete old dir-dir now!!![yes]"
read cmd
case $cmd in
"yes"|"YES"|"Yes"|"")
rm -rf $dirpath
;;
*)
exit 0
;;
esac
fi
mkdir $filepath
mkdir $dirpath
echo -n "Please input a path, please, please, please......"
read path
if [ ! -d $path ]
then
echo "what are you doing"
exit 0
fi
filecount=0
dircount=0
filelist=`ls $path`
for file in $filelist
do
if [ -d $path/$file ]
then
dircount=`expr $dircount + 1`
cp -a $path/$file $dir-dir
elif [-d $path/$file ]
then
filecount=`expr $filecount + 1`
cp $path/$file $file-dir
fi
done
echo "file: $filecount"
echo "directory: $dircount"