Skip to content
Navigation Menu
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
Description
Purpose of the issue
- Bug report (encountered problems/errors)
- Feature request (request for new functionality)
- Question
Version Information
1.3.14
Windows 10 Pro 1803
Description of the issue
When I start cmder using the provided init.bat
I get following error
I have traced it down to the following line where it starts to throw errors i.e «The input line is too long»
if exist «%GIT_INSTALL_ROOT%\cmd\git.exe« %lib_path% enhance_path «%GIT_INSTALL_ROOT%\cmd« %path_position% |
I tried to fix it somehow, but I’m not a batch script expert. Right now I have reverted it to the original init.bat.
Заметки
6) Инициализация числового типа данных
Переменную числового типа можно инициализировать изначально как строковой тип.
Это будет полезно, когда мы не знаем заранее, попадет ли в нее вообще значение.
Например,
Bash | ||
|
Не выдаст ошибку. Переменная n просто уничтожится.
Bash | ||
|
Приведет к синтаксической ошибке в строке № 3.
7) EOL в цикле FOR — правильный порядок модификаторов
EOL — это модификатор цикла, который определяет знак комментария.
Если такой знак встречается первым в строке разбираемого файла, цикл пропускает данную строку.
Code
;Эта строка будет опущена при разборе циклом for /f %%a in (file.txt) do echo.%%a А; эта будет напечатана
По-умолчанию в EOL установлен знак — точка с запятой ( ; )
Чтобы установить пустой знак (без пропуска комментариев), EOL должен обязательно стоять последним среди модификаторов:
Bash
for "UseBackq delims= eol=" %%a in ("file.txt") do Echo.%%a
Иначе, в отличие от модификатора delims, EOL примет за знак комментария символ пробела.
Bash | ||
|
Как проверить — существует ли папка (именно папка, а не файл).
Добавляем в конец имени бекслеш (\)
Bash
if exist "c:\folder\" echo Папка folder существует& exit /B if exist "c:\folder" echo Файл folder существует& exit /B echo Ни папка, ни файл под именем folder не существуют
Тоже самое касается копирования файлов в папку.
Если такая папка не существует файл будет скопирован в предыдущий каталог с новым именем (предполагаемым названием этой папки).
Мало того теперь и папку нельзя будет создать (
ведь в одном каталоге не могут существовать папка и файл с одинаковым именем!
)
Чтобы обойти эту случайную (досадную) ошибку, дописываем в конец целевого каталога бекслеш (\)
Bash
copy "file.txt" "c:\folder\" if %errorlevel% neq 0 echo Возникла ошибка
Конечно, лучше заранее побеспокоится, чтобы создать каталог, или использовать команду XCOPY,
но ведь разные ситуации бывают, не правда ли?
9) Использовать UseBackQ при чтении содержимого файла, имя которого может меняться
Есть 2 варианта опций цикла FOR, которые обеспечивают чтение содержимого файла построчно:
Bash
for /f "delims=" %%a in (file.txt) do echo %%a
Bash
for /f "UseBackQ delims=" %%a in ("file.txt") do echo %%a
В этом варианте все равнозначно.
Но, если вместо file.txt подставить переменную, имя которой (или путь) будут содержать пробелы (а мы заранее можем и не знать), 1-я конструкция не подойдет и будет сначала разбивать строку по пробелам, а уж затем искать данный файл.
Поэтому конструкция с модификатором UseBackQ здесь наиболее приемлема.
Рекомендации
10) Не использовать && после команды Del.
Del возвращает ErrorLevel 0 при возникновении ошибок вида «Отказано в доступе».
Используйте вместо этого конструкцию If not exist
Bash
::Так не рекомендую del file.txt&& ren file2.txt file.txt ::Так следует делать del file.txt if not exist file.txt (ren file2.txt file.txt) else (echo файл file.txt занят другой программой)
11) Внимательно выбирайте имя для BAT(CMD)-файла
Имя не должно носить название распространенных программ и тем более внутренних команд CMD.
Иначе рано или сразу Вы получите зацикливание (вызов батником самого себя).
Вырезка из темы: Неоднозначный ответ ping
Сообщение от gimntut
Порядок исполняемых расширений задаётся переменной PATHEXT
Его можно менять и расширять.
Сначала ищется подходящий исполняемый в текущей папке, а потом уже ищет по переменной Path.
Поэтому до .\ping.bat доходит раньше, чем до %SYSTEMROOT%\SYSTEM32\ping.exe.
Поэтому если хотим, чтобы запускался именно ping.exe, то так и нужно писать
12) После перехода в другой каталог проверять успех операции
Иначе может получиться, что Вы работаете совершенно с другой папкой.
Причины могут быть разные, например, доступ к папке запрещен, не хватает прав, или папка не существует…
Bash
::Переход в другой каталог с одновременной сменой диска (если такова требуется) chdir /d "d:\test" ::Проверка, достигли ли цели if %errorlevel%==0 Echo Выполняем нужные действия ::Или, как вариант, проверяем где сейчас находимся if "%cd%"=="d:\test" Echo Продолжаем банкет :^)
Заметки
13) Сохранение концевого пробела в переменную
Bash | ||
|
14) Обход ошибки «Режим вывода команд на экран (ECHO) включен»
Если есть вероятность попадания под Echo переменной без значения,
сразу после Echo ставим точку:
Будет выведена пустая строка.
15) Граничные значения для числового типа в CMD
Числовой тип в CMD может принимать целые значения в пределах от -2147483647 до 2147483647.
Тем не менее, код возврата может принимать значение на 1 (единичку) меньше минимума. Проверим?
Bash
Call :ErrorLevelMinimal Echo %ErrorLevel% pause&goto :eof :ErrorLevelMinimal exit /b -2147483648
Ошибки
16) Пробелы тоже могут являться частью названия переменной
Частая ошибка новичков
Bash | ||
|
Добавлено через 15 часов 20 минут
Интересное обсуждение Открывающаяся скобка в командном процессоре
Подключайтесь!
Russian Qt Forum > Forum > Qt > Установка, сборка, отладка, тестирование > Ошибка «Слишком длинная входная строка» при сборке
Страниц: [1] Вниз |
« предыдущая тема следующая тема »
|
Автор | Тема: Ошибка «Слишком длинная входная строка» при сборке (Прочитано 5361 раз) |
|
|||||||||
|
|||||||||
|
|||||||||
Страниц: [1] Вверх |
|
« предыдущая тема следующая тема »
Перейти в:
-
#1
Shell & «Слишком длинная входная строка.»
Выполняю в консоли такую строку:
Код:
D:\web\only\misc>"D:/web/bin/convert.exe" d:/web/only/images/goodsphoto/00000083/_original_83_ -resize 50x50 -quality
85 -sharpen 10 - | "D:/web/bin/composite.exe" -geometry +5+5 -gravity SouthEast d:/web/only/images/logos/label_1.png
- d:/web/only/images/goodsphoto/00000083/cat_x50.jpg
работает на ура
при попытке выполнить её из cli php скрипта получаю
Код:
php create_thumbnails.cli.php
Слишком длинная входная строка.
Как можно решить такую проблему?
-
#2
уменьшить длину строки
разбив ее на части и обзаведясь временным файлом
-
#3
Tor
Спасибо. Так и сделал: вынес чаcть параметров в сгенерированый bat-файл и запускал уже его.
There is a really annoying issue with using command line tools on Windows: the maximum length of the command line passed to cmd.exe is 8192 characters (see http://blogs.msdn.com/b/oldnewthing/archive/2003/12/10/56028.aspx). So you think this is not a problem for you, as you would not pass such a long command line to cmd.exe (the DOS shell under Windows)? Well, if you are using Eclipse (as I do) which generates make files (which is the normal way), then the cmd.exe very likely is involved to call the compiler/linker/etc, indirectly with the usage of make.exe. Compiling files is usually not a problem as it does not hit that 8192 limit. However, it is likely that link phase will end up with an error:
Error in the Problems View
If you have such a problem, there is a solution ….
Failure to Link?
Looking at the Console output, it is clearly the link phase which failed:
Linker failed because of 8192 character limit
So what happened? I’m using source files with a rather long directory path, and many of them (e.g. building the CMSIS library, see “Tutorial: Using the ARM CMSIS Library“). Because that library/project has many, many files which need to be linked, it will fail at the link phase. In my above test example I have a command line length passed to the linker which is 12316 characters long!
The error might be a strange one, maybe saying something like it cannot find or execute an object file. Because the command line gets cut somewhere, the error message reported usually does not give a clear clue.
The problem is not the problem of Eclipse: it is rather the problem of make how much it accepts on the command line and long the command line to the gcc compiler and linker can be. The problem can be easly reproduce with my DIY toolchain and is present in other vendor toolchains like the Freescale Kinetis Design Studio (tried with v2.0.0) on Windows.
💡 CodeWarrior for MCU solves that problem with a custom build tools integration: instead of passing the full set of arguments on the command line, it uses files with the options/commands in it. So it passes the options to the called process with pointing to a file. Unfortunately this is not present in the widely used GNU ARM Eclipse plugins (see support request #25 and support request #32).
Oh yeah, I hear now already the voices singing: “Dude, it’s your fault, why are you using Windows? Use Linux!” because this problem does not exist on Linux. Oh well, do not get me there 😉
The obvious solution is to keep the command line as short as possible, especially for the linker:
- Use short directory names
- Use short file names
- Reduce the command line length with using relative paths instead of absolute file paths
- If this does not help: build part of the application as a library and then link the library with the final application
Needless to say that this is all very time consuming and just a workaround for the problem. The solution is to use the GNU ARM Eclipse Build Tools package instead.
GNU ARM Eclipse Build Tools
Luckily, there is now a solution available for Windows, thanks to the Liviu and the GNU ARM Eclipse work :-). The solution is available from the version v2.6.1 or later of the GNU ARM Eclipse Plugins build tools, and the release notes reads:
“The new Build Tools v2.3 include a better shell version, instead of the Windows cmd.exe, so the annoying 8K limit on command line lengths was removed.”
Oh, wow! So this is the solution is to use these build tools, and then that 8192 character command line limit should be gone? Yes, it is :-)!
Installing the Solution
The latest build (v2.4 at the time of this writing) is available from https://sourceforge.net/projects/gnuarmeclipse/files/Build%20Tools/.
GNU ARM Eclipse Build Tools
Download the setup executable and run it.
GNU ARM Eclipse Build Tools Installer
On my machine, the build tools get installed into
C:\Program Files (x86)\GNU ARM Eclipse\Build Tools\2.4-201503242026\bin
GNU ARM Eclipse Build Tools Installed
Now make sure that these tools are used instead of the ones with the 8192 command line character limit. For Kinetis Design Studio v2.0.0, the build tools are located in these sub folders:
- make.exe is in <kds_2.0.0>\toolchain\bin
- echo.exe and rm.exe are in <kds_2.0.0>\bin
Rename the existing make.exe, rm.exe and echo.exe so you have a backup. Then copy the files from the GNU ARM Eclipse build tools into the KDS bin folder:
GNU ARM Eclipse Build Tools in KDS
Because I have renamed the existing make.exe, rm.exe and echo.exe, they are not found any more and the new versions are used instead with the sh.exe which fixes that annoying Windows problem. And if I do a build now with my long command line, it does works :-):
Success building with GNU and very long command line
Summary
Windows (better, cmd.exe) has a command line length limit of 8192 characters. The GNU ARM Eclipse build tools provided by Liviu have fixed this with a new sh.exe. Using the GNU ARM Eclipse build tools allowed me overcome that Windows limit. The fix is easy to apply: replace the limited cmd.exe based tools with teh GNU ARM Eclipse ones which use the sh.exe.
Happy Shelling 🙂
PS: Liviu, you probably read this, and I know you are using Mac OS, and you are not a fan of Windows environment for good reasons. On behalf of the Windows user community: THANK YOU, THANK YOU, THANK YOU!