shell脚本示例0

吐舌头首先明确几个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"




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值