Command line error too short switch

I have a directory structure similar to the following: ROOT --> Site_01 --> 2015 --> 01 --> more subfolders and files (thousands of log files) --> Sit...

I have a directory structure similar to the following:

ROOT
  --> Site_01
    --> 2015
        --> 01
             --> more subfolders and files (thousands of log files)
  --> Site_02
    --> 2015
        --> 01
             --> more subfolders and files (thousands of log files)
  --> Site_03
    --> 2015
        --> 01
             --> more subfolders and files (thousands of log files)

And somewhere else, I have a possibly existing zip file, whose contents mirror the folder structure described above. What I’d like to do is script a batch file such that it zips up everything under ROOT into the possibly already-existing zip file.

If the zip file does not already exist, I want to create it, and if it does exist, I want to simply add the contents of ROOT to it.

What I’ve tried so far are variants of the following:

D:ROOT>7z -u D:archivelogs_app.zip *  
D:ROOT>7z -up2q2r2x2y2z2w2 D:archivelogs_app.zip *  

I don’t care if there’s a file in ROOT that already exists at the same location in the archive — the already-archived file can simply be overwritten. So, based on my perusal of 7Zip’s Update Switch documentation, I left out all update options. But I get the error: Command Line Error: Too short switch:-u. And for the second, I figure that regardless of state, I want to compress the file and add it to the archive; that command gives me this output and error:

7-Zip [64] 9.38 beta  Copyright (c) 1999-2014 Igor Pavlov  2015-01-03

Command Line Error:
Unsupported command:
D:archivelogs_app.zip

7-Zip

A free file archiver for extremely high compression

  • Summary

  • Files

  • Reviews

  • Support

  • Wiki

  • Tickets ▾

    • Support Requests
    • Patches
    • Bugs
    • Feature Requests
  • News

  • Discussion

Menu

7-Zip for Linux


Created:

2021-03-10

Updated:

2021-10-18

  • Laszlo Toth

    Hi Igor,
    I re-started to recover my 73 GiB archive created earlier with p7zip under Linux now with 7-Zip 21.02 alpha under Win 10. I pushed from the drop down menu ‘Open inside #’ item and I got 52 different zip files now. (se attached) I can see the offsets and the last zip may contains my zipped stuff.
    Can you please provide me with an idea what shall I do to unpack the complete package? Thanks.
    Or is there any tricks to concatenate zip file parts and unzip the whole stuff?

    Thumbnail

    • Igor Pavlov

  • h11p5g

    Hi Igor,

    for speed comparison (default setting):
    LZMA: ~ 6 MB / s
    LZMA2 -mmt8: ~ 11 MB / s
    RAR5 -s: ~ 21 MB / s

    The sample data is 483 MB.
    I have i7-4790K and 7z can use 8 threads. It’s too slow for 8 threads.
    But it’s faster than p7zip.

  • h11p5g

  • HITCHER

     

    Last edit: HITCHER 2021-03-10

    • HITCHER

      FX-8300 @3,6GHz (3,9/4,2GHz turbo):

      on Debian 11 (bullseye)

       

      Last edit: HITCHER 2021-03-13

    • Igor Pavlov

      The hardware instruction crc32 is very fast on Cortex-A72. Probably it can be executed with latency=1 on A72.
      And Cortex-A57 shows 3 cycles latency for same instruction.
      So A72 is 3 times faster there. All another things look similar for performance of A72 and A57, but A72 in Pi4 doesn’t support SHA and AES instructions.

      That CRC32 test is pretty fast on A72 to show the bandwidth of RAM and cache when the block is large.
      You can run it on arm64 so:

      7zz b -mm=CRC32:64 -mtime=2
      

      Maybe you can use similar CRC32 benchmark also to catch exact lines with crash. You can change the time with -mtime=2 for seconds or with -mtimems=100 for ms, if you want faster runs.

      And what is that crash on 2 GHz?
      Is it some error message from 7-Zip program or it’s some crash on system level?

       

      Last edit: Igor Pavlov 2021-03-10

      • HITCHER

        The crash was black screen and what appears to be an instant shutdown of SOC.
        Strange, because on ARM64 it worked stable so far oc 2GHz, but not for this 32bit code.

        My pi has heatsink and fan attached, and a very powerful PSU (not usb-c), so this was not the problem. It seems, the problem was GPU OC setting of 650 MHz, i changed that to 550, maybe that has caused a deadlock before (GPU doesn’t do anything for 7zz, but on pi it also has the memory controller). Now it’s working on 2GHz cpu clock.

        On Ubuntu20.10 for Raspberrypi ARM64, you can add architecture armhf to dpkg and to repositories, and install the required libraries, libc6 and libstdc++ to get the 32bit armhf binary working.
        https://wiki.debian.org/Multiarch/HOWTO

        I have added below raspberrypi4 armhf and the ARM64 benchmarks from the other thread for comparison.

         

        Last edit: HITCHER 2021-03-12

      • HITCHER

        I installed multiarch armhf + ARM64 on ubuntu 20.10 ARM64 for pi4, and was able to run 32 Bit code there too, now even with overclock settings (which crashed on raspbian 32Bit):

        [pi4]
        max_framebuffers=2
        
        over_voltage=5
        arm_freq=2000
        gpu_freq=650
        
        hdmi_enable_4kp60=1
        

        Still i think GPU clock 650 is considered to be unstable, since it crashed before on raspian.
        Something else is different. On raspian there was 32Bit kernel.

         

        Last edit: HITCHER 2021-03-15

  • teoberi

    • teoberi

      I have been using 7-Zip for 64-bit Linux x86-64 (AMD64) since the first day of this version’s release. I replaced the jinfeihan57/p7zip fork in the Amavis configuration on my test server without any problems, nothing recorded in the logs.
      +1 for adding Zstandard.

      • teoberi

        However, I found something in /var/log/syslog

        <…>kernel: process ‘/usr/bin/7zz’ started with executable stack

        Should I worry?

         

        Last edit: teoberi 2021-04-09

  • Sam Tansy

    So what’s the difference between 7zip and p7zip?

    And what are requirements for run except GLIBC_2.16 and CXXABI_1.3.9?

    • sNop

      I want to know this too, what is the difference? Of course in summary.

  • Radon Rose

    Don’t know if this is intentional, but the -o switch works in a funny way. Let’s say I downloaded the source code for 7z and wanted to extract it in a directory same as the filename of the archive. Adding a space between -o and the output directory breaks the switch.

    $ ~/.7z2101-linux-x64/7zz x 7z1900-src.7z -o ./7z1900-src
    Command Line Error:
    Too short switch:
    -o
    $ ~/.7z2101-linux-x64/7zz x 7z1900-src.7z -o./7z1900-src
    
    7-Zip (z) 21.01 alpha (x64) : Copyright (c) 1999-2021 Igor Pavlov : 2021-03-09
     compiler: 9.3.0 GCC 9.3.0 64-bit locale=en_US.UTF-8 Utf16=on HugeFiles=on CPUs:4 Intel(R) Core(TM) i7-5550U CPU @ 2.00GHz (306D4),ASM,AES
    
    Scanning the drive for archives:
    1 file, 1071569 bytes (1047 KiB)
    
    Extracting archive: 7z1900-src.7z
    --
    Path = 7z1900-src.7z
    Type = 7z
    Physical Size = 1071569
    Headers Size = 19163
    Method = LZMA:23
    Solid = +
    Blocks = 1
    
    Everything is Ok
    
    Files: 1172
    Size:       7339189
    Compressed: 1071569
    

    I’m also uploading my benchmark.

    • Sam Tansy

      Command Line Error:
      Too short switch:
      -o

      It always worked like that.
      Maybe it should be stated in documentation that this option does not allow space after switch.

      • Igor Pavlov

        It’s same rule for all switches in 7-Zip.
        And you can move switches to any place in command line among non switches.

  • Jared B.

    Just wanted to drop another note of thanks for the native Linux support. Very welcome and surprising news, especially considering p7zip seems to be abandoned at this point.

     

    Last edit: Jared B. 2021-03-11

  • Sam Tansy

    Does it involve some significant changes in code or just prepared scripts and makefiles necessary to compilation?

    • Igor Pavlov

      I also compiled 7-Zip code with p7zip’s scripts for test purposes. So it will be possible to merge both code versions.

       

      Last edit: Igor Pavlov 2021-03-11

  • adeniz

    Linux 5.11.5-zen1-1-zen x86_64

  • Marcin Zajaczkowski

    I’ve just checked it on Fedora 33 and it worked fine. However, I’ve noticed that with -p it prints a given password while typing. Is there a switch to hide it?

    In addition to that, for -p there was a nice feature in p7zip to ask twice for manually typed (and hidden) password. Thanks to that you didn’t need to write the password once and then test the archive to verify that you entered the right password. Typing it twice was very effective in my case to eliminate typos. IT would be nice to have it also available in the new version.

  • Francesco Minnocci

    Arch Linux, 5.11.5-zen1-1-zen x86_64:

  • Hammerfest

    I hope he has reached out to you instead of just posting and claiming to not want to post it publicly.
    Considering you don’t normally release source until its final is this scare mongering (if he hasn’t reached out)?

    He has since gone on to «elaborate» on his «strongly» worded first post, naturally he didn’t understand the power of words with regards to the OBVIOUS worry it would cause when talking about 7zip source code and «strongly» recommended it be run in a sandbox right when the latest release came out…

    ZING

     

    Last edit: Hammerfest 2021-03-12

  • lwy08


Log in to post a comment.

I have 7 zip installed on windows machine. I have to extract .gz files into .txt files. I am not able to find a suitable command to do that. I tried below :

7za e %SFTP_INDIR%DFUView.20150531060116.gz -o D:BatchBatch_FWKdatainDFUView.txt

Got errors using this — ‘7za’ is not recognized as an internal or external command,operable program or batch file. Need help.

  • windows
  • script
  • 7-zip
  • extract

Hennes's user avatar

Hennes

64.3k7 gold badges110 silver badges165 bronze badges

asked Jun 5, 2015 at 19:42

Novice's user avatar

NoviceNovice

431 gold badge4 silver badges8 bronze badges

3

  • Make sure 7za.exe is in your path, or in the directory in which you’re running the command.

    Jun 5, 2015 at 19:46

  • I tried with this command again : D:Batch7-Zip7z.exe %SFTP_INDIR%DFUView.20150531060116.gz -o D:BatchBatch_FWKdatainDFUView.txt and this gave error : Command Line Error: Too short switch: -o

    Jun 5, 2015 at 20:09

  • You’ve specified a switch for 7z but where’s the command? Type 7za /? or read the manual.

    Jun 5, 2015 at 20:25

  1. 02-07-2022, 12:20 AM


    #1

    XML2005 is offline


    Registered User


    7-zip Incremental Backup command returns «Too short switch: -u»

    I am trying to learn how to do a differential backup, using 7-zip command line processing from within Excel VBA.

    My original backup, created with 7-zip WScript.Shell command line, is named «G:Bkup20220206-224747myFiles.7z«.

    I want all files changed/added after the latest backup to be added to myFiles.7z.

    The following code returns the error: «Too short switch: =u«.

    Set oShell = VBA.CreateObject(«WScript.Shell»)
    oShell.Run(«C:Program Files7-Zip7zg.exe» a -pmypassword -u -mhe=on «G:Bkup20220206-224747myFiles.7z» «C:UsersMyUserNameDocumentsPgmNameData*», WindowStyle:=0, WaitOnReturn:=1)

    What am I doing wrong, please?

    Thank you!


  2. 03-31-2022, 10:36 PM


    #2

    Re: 7-zip Incremental Backup command returns «Too short switch: -u»

    From 7z’s help

    Command Line Syntax
    7z command [switch…] base_archive_name [arguments…]

    The executable

    «C:Program Files7-Zip7zg.exe» a -pmypassword -u -mhe=on «G:Bkup20220206-224747myFiles.7z» «C:UsersMyUserNameDocumentsPgmNameData*»

    According to the readme.txt, 7zg.exe is the GUI module; while this I believe works also at the command line, you probably wanted the 7z.exe (Command line version).

    command

    «C:Program Files7-Zip7z.exe» a -pmypassword -u -mhe=on «G:Bkup20220206-224747myFiles.7z» «C:UsersMyUserNameDocumentsPgmNameData*»

    The first option after 7z.exe tells 7z which command to do; you have a for Add, you probably wanted u for Update

    switch…

    «C:Program Files7-Zip7z.exe» u -pmypassword -u -mhe=on «G:Bkup20220206-224747myFiles.7z» «C:UsersMyUserNameDocumentsPgmNameData*»

    Looks like you used three switches

    • -pmypassword this one looks fine to set the password
    • -mhe=on this one looks fine to turn on file name encryption
    • -u this one could use some help

    -u (Update options) switch

    «C:Program Files7-Zip7z.exe» u -pmypassword -u -mhe=on «G:Bkup20220206-224747myFiles.7z» «C:UsersMyUserNameDocumentsPgmNameData*»

    Syntax
    -u[-]state_action…[!{new_archvie_name}]

    the dash -u- turns off updates, probably not what you want
    states and actions come in pairs, the state describes the kind of file and the action describes what to do with a file in that state

    state

    on disk

    in archive

    p not selected
    q doesn’t exist exists
    r exists doesn’t exist
    x older newer
    y newer older
    z same same
    w ? ?

    action

    description

    0 drop
    1 keep
    2 add
    3 NUKE

    the default for the «a» command was -up1q1r2x2y2z2w2, we changed to the «u» command’s default -up1q1r2x1y2z1w2

    p — zipped file didn’t match the *.* selection 1 — keep the zipped one
    q — zipped, but not on disk 1 — keep the zipped one
    r — on disk, not zipped 2 — zip from disk
    x — on disk is old 1 — keep the zipped one
    y — on disk is new 2 — zip from disk
    z — disk matches zip 1 — keep the zipped one
    w — size is different, but update dates are the same 2 — zip from disk

    This looks fairly sane/non-destructive, and probably what you wanted to do; however for the sake of argument let’s say if it’s in the archive but not on disk you want to throw away the backup copy -uq0
    (don’t -uq3 nuke it, that’s even worse since it will force the existing disk copy to be deleted when the archive is unzipped)

    we could also at this point call the new zip something else -uq0!G:LostSomethingElse.7z, but I’m guessing you didn’t want to

    base_archive_name

    «C:Program Files7-Zip7z.exe» u -pmypassword -uq0 -mhe=on «G:Bkup20220206-224747myFiles.7z» «C:UsersMyUserNameDocumentsPgmNameData*»

    I’ll assume this is the zip file to be updated

    arguments…

    «C:Program Files7-Zip7z.exe» u -pmypassword -uq0 -mhe=on «G:Bkup20220206-224747myFiles.7z» «C:UsersMyUserNameDocumentsPgmNameData*»

    Again I’ll assume this filters for the files you wanted to archive/update. (note, switches can be arguments so that they can go after the base zip name if you’d prefer)

    That about wraps it up for the 7zip part, and why 7zip is saying -u the switch(not u the command) is missing the section where you tell it what you want done.

    You of course can find all of this and much more in 7zip’s GUI help file as well.


    Edit: so I removed the -uq0 from the code block just incase you were just TLDR, and went for the copy / past / delete my files option.

    Last edited by Gregor y; 03-31-2022 at 10:48 PM.

    Reason: make it safer

    If it’d make you feel better using my answer because of my street cred, then you can go ahead and click Add Reputation below to improve it.


Comments

@slyshykO

@Nightwalker-87
Nightwalker-87

changed the title
win32: Wrong command line for 7z.exe in Findlibusb.cmake

win32: Compilation error in cmake (Find_libusb & GNUInstallDirs)

Apr 20, 2020

Nightwalker-87

added a commit
that referenced
this issue

Apr 21, 2020

@Nightwalker-87

- Include of GNUInstallDirs module
- Removed old ci-leftover in Makefile

Extraction of downloaded libusb archive failed due to wrong command 
option formatting since commit a8c1f41.
(Fixes #936)

Nightwalker-87

added a commit
that referenced
this issue

Apr 21, 2020

@Nightwalker-87

- Include of GNUInstallDirs module
- Removed old ci-leftover in Makefile

Extraction of downloaded libusb archive failed due to wrong command 
option formatting since commit a8c1f41.
(Fixes #936)

Nightwalker-87

added a commit
that referenced
this issue

Apr 21, 2020

@Nightwalker-87

- Include of GNUInstallDirs module
- Removed old ci-leftover in Makefile
- Name pattern for libusb detection

Extraction of downloaded libusb archive failed due to wrong command 
option formatting since commit a8c1f41.
(Fixes #936)

Nightwalker-87

added a commit
that referenced
this issue

Apr 21, 2020

@Nightwalker-87

- Include of GNUInstallDirs module
- Removed old ci-leftover in Makefile
- Name pattern for libusb detection

Extraction of downloaded libusb archive failed due to wrong command 
option formatting since commit a8c1f41.
(Fixes #936)

Nightwalker-87

added a commit
that referenced
this issue

Apr 21, 2020

@Nightwalker-87

- Include of GNUInstallDirs module
- Removed old ci-leftover in Makefile
- Fixed name pattern for libusb detection

Extraction of downloaded libusb archive failed due to wrong command 
option formatting since commit a8c1f41.
(Fixes #936)

@Nightwalker-87
Nightwalker-87

changed the title
win32: Compilation error in cmake (Find_libusb & GNUInstallDirs)

win32: Compilation error in cmake (p7zip, Find_libusb, GNUInstallDirs)

Apr 21, 2020

@stlink-org
stlink-org

locked as resolved and limited conversation to collaborators

May 29, 2020

Архивы 7z не так популярны, как Zip, но всё же пользуются спросом у пользователей. Для сжатия используется эффективный алгоритм LZMA2, на 10-40% превосходящий Deflate (Zip). В дистрибутивах Linux обычно отсутствует предустановленный архиватор для работы с 7z.

Мы рассмотрим несколько как выполняется распаковка 7z Linux. Помимо этого, приведём примеры использования консольной утилиты 7z.

TtB10oLUqrW9QAAAABJRU5ErkJggg==

В начале архива стоит «волшебное слово» 7z (377A в HEX)

Архивы формата 7z практически не используются разработчиками для распространения программ. Их выбирают обычные пользователи в виду того, что алгоритм LZMA2 обладает хорошей степенью сжатия и при этом не требует покупки архиватора, как тот же RAR.

К плюсам этого формата также можно отнести и то, что с ним работает большое количество архиваторов на всех операционных системах, хотя до универсальности Zip он не дотягивает.

Как распаковать 7z в графическом интерфейсе

AS0BbNfEHRUrAAAAAElFTkSuQmCC

Архиватор PeaZip может открыть и распаковать архив 7z

Так как 7z использует метод сжатия LZMA2 (применяется в tar.xz), то нет ничего удивительного в том, что его поддерживает большинство архиваторов, доступных на Linux. Для распаковки нажмите кнопку Извлечь/Распаковать (Extract). Также вы можете перетащить файлы в папку или на рабочий стол, если эта функция доступна в вашей оболочке.

Список архиваторов, поддерживающих распаковку 7z:

  • File Roller (GNOME).
  • Engrampa (Mate).
  • Ark (KDE).
  • PeaZip.
  • Xarchiver.
  • p7Zip-GUI.

Как распаковать 7z в терминале

Для того, чтобы распаковать архив 7z в терминале, необходимо установить утилиту p7zip, которая также используется в архиваторах с графическим интерфейсом. Команда для установки в Debian/Ubuntu:

sudo apt install p7zip-full

Команда для установки в Red Hat/Fedora:

sudo yum install p7zip p7zip-plugins

Команда для установки в Archlinux/Manjaro:

sudo pacman -Sy p7zip

После этого вам станут доступны команды p7zip и 7z. Последняя содержит большее количество аргументов. Также стоит упомянуть о том, что у программ разный синтаксис, но общая библиотека. Для распаковки с помощью p7zip используйте команду:

p7zip -d имя_файла.7z

В том случае, если архив будет зашифрован, утилита сама спросит пароль без необходимости добавлять аргументы. К сожалению, выбрать конечную папку с p7zip нельзя.

xn7wtdAMP5AAAAABJRU5ErkJggg==

p7zip/7z задаcт вопросы, если это необходимо

Команда 7z позволяет не только распаковать, но и запаковать файлы, применив при этом множество параметров.

Вот основные аргументы команды 7z:

  • x — распаковать все файлы, с учётом вложенности.
  • e — распаковать все файлы, без учёта вложенности.
  • o — указать каталог для распаковки.
  • l — посмотреть содержимое архива.
  • r — обрабатывать каталоги при использовании фильтров.
  • i — показать информацию о поддерживаемых форматах и алгоритмах сжатия.

А теперь рассмотрим пару примеров использования этих команд. Эта команда просто распакует архив в текущую папку:

7z x имя_файла.7z

Распаковать только нужные файлы можно с помощью этих команд:

7z l имя_файла.7z -r *.db

7z e имя_файла.7z -r файл_1.db

В этом примере мы сначала нашли все файлы с расширением .db, а затем извлекли файл_1.db рядом с архивом с помощью команды e, которая распаковывает файлы без учёта вложенности. С помощью этой команды архив будет распакован в папку:

7z x имя_файла.7z -o имя_папки

Как видите, имя папки вводится без пробела. В этом примере папка будет создана рядом с архивом.  Также вы можете задать другую папку, например, домашний каталог:

7z x имя_файла.7z -o /home/имя_пользователя/

Стоит отметить, что архиватор не понимает ~. Если вы решите использовать это сокращение, то будет создана папка с именем ~. Теперь вы знаете как разархивировать 7z linux.

Выводы

Для того чтобы распаковать 7z в Linux необходимо установить архиватор, поддерживающий этот формат. Среди графических одним из лучших будет PeaZip. Консольных архиваторов не так много и для работы с 7z следует использовать p7zip, который также содержит архиватор 7z.

Creative Commons License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

У меня проблемы с получением файла .7z для извлечения через Powershell.

Моя функция PowerShell выглядит так:

function unzip($file, $destination)
{
    & 'C:Program Files7-Zip7z.exe' x -y $file -o"$destination";
}

Я получаю такую ​​ошибку:

7z.exe : 
At restoreQA.ps1:26 char:5
+     & 'C:Program Files7-Zip7z.exe' x -y $file -o"$destination";
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

Command Line Error:
Too short switch:
-o

Кажется, есть какая-то ошибка синтаксического анализа, но я пробовал все разные комбинации, чтобы заставить ее работать.

Любые идеи о том, почему это не работает?

1 ответ

Лучший ответ

Вы должны заключить -o в кавычки:

& 'C:Program Files7-Zip7z.exe' x -y $file "-o$destination"


8

David Martin
18 Мар 2016 в 16:26

Понравилась статья? Поделить с друзьями:
  • Command line error d8021 invalid numeric argument error
  • Command line error d8016 ehs and clr
  • Command line error d8003 missing source filename
  • Command killed due to buffer error
  • Command error please resend command rtu5024