9.1 read命令

read 命令的一般形式为:

read variables

该命令执行时,Shell会从标准输入中读取一行,然后将第一个单词分配给variables中列出的第一个变量,第二个单词分配给第二个变量,以此类推。如果行中的单词多于列表中的变量,那么多出的单词全部分配给最后一个变量。例如,下列命令:

read x y

会从标准输入中读入一行,将第一个单词分配给变量x,将行中余下的内容分配给变量y。安照这样的处理逻辑,下列命令:

read text

会读取并将一整行保存到shell变量text中。

9.1.1 文件复制程序

下面编写一个简化版的cp命令程序,借此实践一下read命令。

[root@centos7_c1 linux]# cat mycp 
#
#复制文件
#

if [ "$#" -ne 2 ] ; then
	echo "Usage: mycp from to"
	exit 1
fi

from="$1"
to="$2"

#
#检查目标文件是否已经存在
#

if [ -e "$to" ] ; then
	#echo命令会自动在最后一个参数后面加上一个用于终止的换行符,在echo命令的最后加上特殊转义字符\c可以阻止这种情况
	echo "$to already exists; overwrite (yes/no)? \c"
	read answer

	if [ "$answer" != yes ] ; then
		echo "Copy not performed"
		exit 0
	fi
fi

#
#如果目标文件不存在或者用户输入yes
#

cp $from $to	#执行复制操作
[root@centos7_c1 linux]#

9.1.4 mycp最终版本

想要mycp接受任意数量的参数,可以使用下面的方法:
1、从命令行中获取除最后一个参数之外的其他参数,将其保存在shell变量filelist中。
2、将最后一个变量保存在变量to中。
3、如果shell中 获取 存储过程的 out值 postgresql shell获取命令的输出_linuxto是目录,对shell中 获取 存储过程的 out值 postgresql shell获取命令的输出_centos_02to中。
下面给出详细代码:

[root@centos7_c1 linux]# cat mycp 
#
#复制文件 最终版
#

numargs=$#
filelist=
copylist=

#
#处理参数,将除最后一个参数之外的其他参数保存在变量filelist中
#

while [ "$#" -gt 1 ] ; do
	filelist="$filelist $1"
	shift
done

to="$1"

#
#如果少于两个参数,或者多于两个参数且最后一个参数不是目录,则发出错误信息
#

if [ "$numargs" -lt 2 -o "$numargs" -gt 2 -a ! -d "$to" ] ; then
	echo "Usage: mycp file1 file2"
	echo "	     mycp file(s) dir"
fi

#
#遍历filelist中的每个文件
#
#

for from in $filelist ; do
	#
	#查看目标文件是否为目录
	#

	if [ -d "$to" ] ; then
		tofile="$to/$(basename $from)"
	else
		tofile="$to"
	fi

	#
	#如果文件不存在或者用户要求进行覆盖,则将其添加到变量copylist中
	#
	
	if [ -e "$tofile" ] ; then
		echo "$tofile already exists; overwrite (yes/no)? \c"
		read answer

		if [ "$answer" = yes ] ; then
			copylist="$copylist $from"
		fi
	else
		copylist="$copylist $from"
	fi
done

#
#进行复制操作——复制之前先判断待复制文件是否为空
#

if [ -n "$copylist" ] ; then
	cp $copylist $to
fi



[root@centos7_c1 linux]#