"the input line is too long,☺was unexpected at this time"解决思路
问题描述:
windows环境下在CMD窗口运行批处理文件(.bat),批处理文件中有10000次循环,每次在第120次循环处便报错:"the input line is too long,☺ was unexpected at this time",即“输入行太长,此时不应有☺”;
可能原因:
”On computers running Microsoft Windows XP or later, the maximum length of the string that you can use at the command prompt is 8191 characters. On computers running Microsoft Windows 2000 or Windows NT 4.0, the maximum length of the string that you can use at the command prompt is 2047 characters.
This limitation applies to the command line, individual environment variables (such as the PATH variable) that are inherited by other processes, and all environment variable expansions. If you use Command Prompt to run batch files, this limitation also applies to batch file processing.”--摘自《Command prompt (Cmd. exe) command-line string limitation》
简而言之,是说命令提示框对每个命令行的最大长度有限制,WinXP及以后系统其最大长度是8191个字符。这种限制不仅对命令行有效,对于命令提示框下执行批处理文件同样有效。应特别留意环境变量(比如PATH变量等)是否超过该限制。
针对这个问题网上有如下建议:
- Modify programs that require long command lines so that they use a file that contains the parameter information, and then include the name of the file in the command line.
- Use shorter names for folders and files.
- Reduce the depth of folder trees.
解决思路:
1、按上述建议缩短文件名及目录树深度等,然后并不奏效;
2、同时继续运行以重现问题,发现问题依旧;
一个小技巧:直接运行bat批处理文件,出错时会DOS框会直接消失而看不到出错消息,这时可以在批处理文件所在目录空白处,按住Shift+鼠标右键,在此处打开命令窗口,然后把批处理文件拖进来执行,这样报错时便会看到错误信息;这比加pause并echo显示变量值的方式更方便一些。
问题依旧时,根据前面分析以及”输入行太长“的信息,开始怀疑是批处理文件执行过程中某个命令行太长超出限制。但为什么之前都正常,偏偏是循环到第120次就出错呢,为什么呢?立马横向做实验对比,在另一台远程机器上同时反复实验,发现同样的问题,不过是执行到第133次时报同样的错。总结一下,同样的错误只不过循环进行的次数不一样,说明什么呢?多问下自己为什么,因为所有问题肯定都是能解决的。自己会想到,之前循环时正常,但循环到第120次(133次)时报错,说明有某行命令开始时长度符合,但随着循环的进行,它在递增,到第120次(133次)循环时递增到长度长限,从而触发”输入行太长“的错误。
3、针对上一步的假设进一步寻找原因,进而锁定PATH环境变量;
另一个小技巧:搜索中文的”输入行太长,此时不应有☺“找不到合适思路,不妨搜索英文的”the input line is too long, ☺ was unexpected at this time",可能就会有收获。很幸运找到了一些信息:
“I have had this same problem when executing a build script in a cmd window. After about 13 times I got that same error. The build script had to make sure that vcvarsall.bat was run so it executed vcvarsall.bat every time.
vcvarsall.bat is not smart enough to only add things to the path
if they are not already there so a bunch of duplicate entries were added.
My solution was to add an if defined check on an environment variable which I know is set by vcvarsall.bat...
if not defined DevEnvDir (
call vcvarsall.bat
)
Check your path environment variable after each run and see if it is growing. If it is and there are duplicates, you will need to be smart about adding stuff to the path
. There are several ways to be smart about it.
即在每一次运行时检查path环境的值是否也在增长,如果发现path里有重复项,那么就需要考虑其他更合适的方式来往path里添加内容了。
4、查看循环执行时PATH环境变量的值(用了最笨的办法,直接for里set path即可),发现果然path的值随着循环的执行而变大,从而定位到脚本中相应代码,进行修改。
排错时经常做的无非是横向对比,以逐步排除某部分的出错可能性,然后结合其他方式来定位错误。
参考资料:1-“Input line is too long” error in BAT File ;2-Command prompt (Cmd. exe) command-line string limitation ;(这两个参考资料即上述引用出处,很有帮助)