linuxshell之脚本优化 [操作系统入门]

编程

vi file_can_execute_or_not1.sh
#!/bin/bash

#判断输入的参数个数是否为两个

if [ $# -lt 2 ]
then
echo "The num of parameter is not right! "
exit 0
fi

#判断用户输入的第一个文件是否可以读
if [ ! -f "$1" ]
then
echo "Unable to find the file $1"
fi

#判断用户输入的第一个文件是否可执行
if [ ! -x "$1" ]
then
echo "Unable to execute the file $1 !"
else
echo " The file $1 can be executed!"
fi


#判断用户输入的第二个文件是否可以读
if [ ! -f "$2" ]
then
echo "Unable to find the file $2"
fi

#判断用户输入的第二个文件是否可执行
if [ ! -x "$2" ]
then
echo "Unable to execute the file $2 !"
else
echo " The file $2 can be executed!"
fi

./file_can_execute_or_not1.sh
The num of parameter is not right!

./file_can_execute_or_not1.sh file1 file2
Unable to execute the file file1 !
Unable to find the file file2
Unable to execute the file file2 !

#优化后的脚本
vi file_can_execute_or_not2.sh
#!/bin/bash

#判断输入的参数个数是否为两个

if [ $# -lt 2 ]
then
echo "The num of parameter is not right! "
exit 0
fi

#使用for循环判断输入的文件是否执行
for fname in "$@"
do
if [ -f "$fname" -a -x "$fname" ]
then
echo "The file $fname can be executed"
elif [ ! -f "$fname" ]
then
echo "Unable to find the file $fname"
else
echo "Unable to execute the file $fname !"
fi
done

./file_can_execute_or_not2.sh
The num of parameter is not right!
./file_can_execute_or_not2.sh file1 file2
Unable to execute the file file1 !
Unable to find the file file2

linux shell 之脚本优化

以上是 linuxshell之脚本优化 [操作系统入门] 的全部内容, 来源链接: utcz.com/z/519518.html

回到顶部