有时候看似天衣无缝的代码遇到极具创意的用户是不得不低头的
且看下面一段简单的shell代码,检查用户输入如果是合法的文件,然后做一个copy
-r 测试文件存在且可读
-d 检测是否是目录
如果文件存在且可读而且不是目录,(这里不关心文件内容),那么这个输入是否合法呢?
#!/bin/sh echo "Enter the name of the new licence key file" echo "licencekeyfile=\c" read _afile if [ ! -r $_afile ] then echo "File does not exist" exit 1 fi if [ -d $_afile ] then echo "Licence key file must be a regular file" exit 1 fi #Copy new licenceKey to /var/sog/etc/.licenses/licenseKey if [ "$_afile" != "/var/sog/etc/.licenses/licenseKey" ] then cp $_afile /var/sog/etc/.licenses/licenseKey fi ...
用户如何break这个貌似天衣无缝的条件检测的?
Enter the name of the new licence key file licencekeyfile=/home/user/.licenses/lic*
如果 /home/user/.licenses/lic* 匹配多个文件的情况下,-r 和 -d 判断都能通过,接下来运行到cp 就杯具了
会报下面这个错:
cp: Target /var/sog/etc/.licenses/licenseKey must be a directory Usage: cp [-f] [-i] [-p] [-@] f1 f2 cp [-f] [-i] [-p] [-@] f1 ... fn d1 cp -r|-R [-H|-L|-P] [-f] [-i] [-p] [-@] d1 ... dn-1 dn
真的佩服用户输入的创意啊,为了避免匹配多个文件的情况,不得不用下面的代码来修bug
matches=`ls $_afile | wc -l | sed 's/ //g'` if [ $matches != 1 ] then echo "Your input of the new licence key file is not valid, it matches $matches files :" ls $_afile exit 1 fi
靠,我们脚本里都有这种错误,,不改了,用户就是我们自己,,,