- Rar linux command line
- Contents
- Key features
- Installation
- Configuration file
- RAR compression examples
- General syntax
- Recursively compress an entire directory structure
- Mixed-mode archives
- Recursively compress many directory structures using a list
- UnRAR examples
- General syntax
- How to Use RAR files in Ubuntu Linux [Quick Tip]
- Extracting RAR Files in Linux
- Step 1: Install unrar package from multiverse repository
- Step 2: Extract RAR files either graphically or via command line
- Creating & Managing RAR files in Linux
- About Ankush Das
- How to Extract (Open) a RAR File in Linux
- Install unrar/rar tool
- 1. Extract (open) rar file
- 2. Extract files with full path
- 3. List content of a RAR file
- 4. Check archive integrity
- 5. Create a rar single file
- 6. Create multiple rar files
- 7. Set password for RAR file
- Conclusion
- Распаковка и создание RAR архивов в Linux. Команды unrar, rar
- Установка UNRAR
- Распаковка RAR-архивов
- Список файлов в архиве
- Протестировать архив
- Распаковать RAR с паролем
- Другие возможности команды UNRAR
- Создание RAR архивов в Linux
- Установка пакета RAR
- Создать RAR архив
- Указать степень сжатия
- Разбить архив на несколько файлов
- Добавить файлы в архив
- Удалить файлы из архива
- Восстановить битый архив
- Создать архив с паролем
- Распаковать архив
- Другие возможности команды RAR
Rar linux command line
RAR (and UnRAR) is the Linux port of the commandline-only version of WinRAR available in both the i686 and x86-64 flavors.
Contents
Key features
- Variable amounts of redundancy («recovery record» or «recovery volumes» both of which are demonstrated below) can be added to an archive, making it more resistant to corruption. Even if parts of an archive are damaged, it is possible to fully recover the stored data if a large enough recovery record exists. On its own, Tar does not have this ability.
- RAR is able to efficiently handle split volumes. Built-in support for multi-volume files enables the unpacking program to simply prompt the user for the next .partXXX RAR file, without the need to manually copy and then rejoin the pieces, or for extracting a file from a single piece without needing all pieces. RAR does not support tapes, as it uses seek and rename operations on its files.
- RAR archives can be of a solid format, in which all of the compressed files are treated as a single data block. Most currently used compression formats (with the exception of the older ZIP) allow solid structuring.
- Strong encryption capabilities. Older versions of the file format used a proprietary algorithm; newer versions use the AES encryption algorithm, a block cipher adopted as an encryption standard by the U.S. government. The only known ways to recover an encrypted file are via dictionary or brute force attacks. In newer versions, password protection can optionally protect filenames too, so that the filenames contained within the archive will not be displayed without the right password.
Installation
Install the rar AUR package for both RAR and UnRAR. Alternatively, install unrar for just UnRAR.
Configuration file
RAR for Linux reads configuration information from the file
/.rarrc (i.e. in the user’s home directory) or if you wish to define a global set of options for all users, in the /etc directory.
The syntax of the file is simply the following string:
For a complete listing and explanation of rar‘s switches, see rar(1) .
RAR compression examples
General syntax
For a complete listing of commands and switches, see the last section of this article or simply run rar .
Recursively compress an entire directory structure
- Task: backup /home/darkhorse to /media/data/darkhorse-backup.rar using 10 % recovery records:
- Explained:
Switch | Action |
a | adds files to archives. |
-r | recurse subdirectories (includes all dirs/files under the parent directory). |
-rr10 | adds recovery records to the archive. This way up to 10% of the compressed archive can become corrupt or unusable, and it will be able to recover the data through parity. |
Mixed-mode archives
You can also use mixed-mode archives which means that file types you specifiy do not get compressed — they simply get stored.
- Task: backup /home/darkhorse to /media/data/darkhorse-backup.rar :
- Explained:
Switch | Action |
a | adds files to archives. |
-r | recurse subdirectories (includes all dirs/files under the parent directory). |
-rr10 | adds recovery records to the archive. This way up to 10% of the compressed archive can become corrupt or unusable, and it will be able to recover the data through parity. |
-m5 | Use the highest level of compression (m0 = store . m3 = default . m5 = maximal level of compression. |
-msjpg;mp3;tar | ignore the compression option and store all .jpg and .mp3 and .tar files. |
Recursively compress many directory structures using a list
- Task: backup /home/darkhorse and /home/palomino and /home/seabiscuit to /media/data/homes-backup.rar .
First create a list (simple text file) containing the various targets. In this example, the list will be three lines long. I named it ‘home-list’ in this example but you can call it anything you want:
UnRAR examples
General syntax
For a complete listing of commands and switches simply run:
Источник
How to Use RAR files in Ubuntu Linux [Quick Tip]
Last updated September 22, 2020 By Ankush Das 32 Comments
Looking for WinRAR in Linux? Here’s how to extract and use RAR files in Linux.
RAR is a quite good archive file format. But, it isn’t the best when you’ve got 7-zip in Linux offering great compression ratios and Zip files being easily supported across multiple platforms by default.
It is one of the most popular archive formats, but, Ubuntu‘s archive manager does not support extracting RAR files nor does it let you create RAR files. It would rather show you this error:
There is no command installed for RAR archive files. Do you want to search for a command to open this file?
Fret not, we have a solution for you. To enable the support to extract RAR files, you need to install UNRAR – which is a freeware by RARLAB. And, to create and manage RAR files, you need to install RAR.
Extracting RAR Files in Linux
Unless you have it installed, extracting RAR files will show you an error “Extraction not performed“. Here’s how it should look like (Ubuntu 18.04):
If you want to resolve the error and easily be able to extract RAR files, follow the instructions below to install unrar.
Step 1: Install unrar package from multiverse repository
Launch the terminal and type in the following command to make sure you have multiverse repository enabled in Ubuntu:
Update the package cache:
Now install unrar package:
Step 2: Extract RAR files either graphically or via command line
After installing unrar, you may choose to type in “unrar” (without the inverted commas) to know more about its usage and how to use RAR files with the help of it.
The most common usage would obviously be extracting the RAR file you have. So, you can either perform a right-click on the file and proceed to extract it from there or you can do it via the terminal with the help of this command:
You can see that in action here:
If the file isn’t present in the Home directory, then you have to navigate to the target folder by using the cd command in Linux. For instance, if you have the archive in the Music directory, simply type in “cd Music” to navigate to the location and then extract the RAR file.
Creating & Managing RAR files in Linux
UNRAR does not let you create RAR files. So, you need to install the RAR command-line tool to be able to create RAR archives.
To do that, you need to type in the following command:
Here, we will help you create a RAR file. In order to do that, follow the command syntax below:
When you type a command in this format, it will add every item inside the directory to the archive. In either case, if you want specific files, just mention the exact name/path.
By default, the RAR files reside in HOME directory.
In the same way, you can update/manage the RAR files. Just type in a command using the following syntax:
To get the list of commands for the RAR tool, just type “rar” in the terminal.
Wrapping Up
Now that you’ve known how to use RAR files on Ubuntu, will you prefer using it over 7-zip, Zip, or Tar.xz?
Let us know your thoughts in the comments below.
Like what you read? Please share it with others.
About Ankush Das
A passionate technophile who also happens to be a Computer Science graduate. You will usually see cats dancing to the beautiful tunes sung by him.
# I’ve made this simple python3 script to extract a file from a .rar file
# and put the data into a folder with the same name of the file in the curent directory.
# The script is very simple, it’s just a quick help if you are interested.
# It has some limitations:
# 1) I renamed the .rar file to be able to execute the program
# 2) It only extract one .rar file at the time
# Requisites:
# * you need to install the unrar program
# JUST RUN: sudo apt install unrar -y
# To run the code, just type:
# python3
# Example: python3 rar-extract.py file_to_extract.rar
import os
import sys
# rename rar file to remove spaces from the name
raw_argv = sys.argv[1]
argv_ws = raw_argv.replace(” “,”_”)
os.rename(sys.argv[1],argv_ws)
#remove the .rar extension from the file
#it will be used to create a new folder
arg = (argv_ws.split(“.”)[0]).replace(” “,”_”)
#create the new folder
current_directory = os.getcwd()
final_directory = os.path.join(current_directory, arg)
if not os.path.exists(final_directory):
os.makedirs(final_directory)
#path to the new flder
path = current_directory +”/”+ arg
#enter the new folder
os.system(“cd ” + path)
# command line to extract the file
terminal_line = “unrar e ” + str(argv_ws) + ” ” + path
Источник
How to Extract (Open) a RAR File in Linux
RAR is a file format used for data compression and archiving. The RAR format supports data compression, error recovery and files archives. It also supports files larger than 4 gigabytes. RAR files can only be created through commercial software. You can extract rar file using free unRAR command line tool in Linux.
By default, unRAR is not being installed on Linux or UNIX distro. You need to install unRAR/rar tools with the help of below linux commands.
Install unrar/rar tool
If you are using Redhat Linux or Centos, then use yum command as follows to install unRAR command.
Listed below are some practical examples of RAR and unRAR command in linux to open,extract and compress files.
1. Extract (open) rar file
If you want to extract all files within the ‘.rar’ file in the current directory run below command
2. Extract files with full path
If you want to extract the files in full path. Run below command
3. List content of a RAR file
To list files inside rar archive file without extracting. Then use ‘l’ option
4. Check archive integrity
To test the integrity of file archive use ‘t’ option
5. Create a rar single file
To create a .rar archive file use ‘a’ option.
6. Create multiple rar files
To compress say ‘file1′, ‘file2′ and ‘file3′ simultaneously, use below command
You can also use the following method to RAR multiple files.
7. Set password for RAR file
While archiving, you can set a password (using -p option). If you omit the password on the command line, you will be prompted with a message “enter password” and the password is case sensitive.
Conclusion
In this tutorial we learned how to use rar/unrar command in linux to open,extract and create rar files. Hope you enjoyed reading this and please leave your comments below.
Источник
Распаковка и создание RAR архивов в Linux. Команды unrar, rar
Рассмотрим, как распаковывать и создавать RAR архивы в Linux.
Формат RAR не популярен в Linux среде. Например, штатные графические менеджеры архивов, которые используются в Linux дистрибутивах, обычно не умеют работать с RAR. Чтобы работать с такими архивами, нужно устанавливать дополнительные пакеты.
Для распаковки RAR архивов в Linux используется бесплатный пакет UNRAR от компании RARLAB.
Для создания RAR-архивов служит пакет с одноименным названием RAR. Не пугайтесь, если увидите предупреждение, что это trial-версия. На самом деле пакет не имеет ограничений на время использования. Это такая же вечная пробная версия, как и WinRAR для Windows.
Установка UNRAR
Сначала установим пакет UNRAR.
Обычно, после того, как вы установили пакет UNRAR, некоторые графические менеджеры архивов автоматически начинают поддерживать файлы в формате RAR, и вы можете распаковать их, просто щелкнув правой кнопкой по файлу в файловом менеджере и выбрав пункт Распаковать (может зависеть от дистрибутива).
Распаковка RAR-архивов
Чтобы распаковать RAR-архив, используя командную строку, выполните следующую команду (вместо archive.rar укажите путь до вашего архива). Архив будет распакован в текущую директорию.
Чтобы распаковать архив в определённую директорию (она должна существовать), укажите ее путь после имени архива (вместо ./data укажите путь до директории, в которую нужно распаковать архив):
Список файлов в архиве
Чтобы получить список файлов в архиве, используется опция l :
Протестировать архив
Чтобы убедиться, что архив «не битый», используется опция t (test). Тестируется целостность каждого файла в архиве и выводится результат для каждого файла.
Распаковать RAR с паролем
Чтобы распаковать архив, защищенный паролем, нужно указать пароль, используя опцию p :
Другие возможности команды UNRAR
Мы рассмотрели только базовые опции. UNRAR имеет больше возможностей.
Приведем список некоторых часто используемых опций:
Опция | Описание |
---|---|
x | Распаковать архив, сохраняя структуру директорий архива. |
e | Распаковать архив. Структура директорий архива не сохраняется. Все файлы распаковываются в одну директорию. Если попадаются файлы с одинаковыми именами, то будет выдан запрос на перезапись/пропуск/переименование файла. |
pПАРОЛЬ | Указать пароль для защищенного архива (password). |
l | Вывести список файлов в архиве (list). |
t | Протестировать целостность архива (test). |
cl | Преобразовать имена файлов в строчные буквы (convert to lower case). |
cu | Преобразовать имена файлов в прописные буквы (convert to upper case). |
kb | Распаковывать все файлы, включая «битые» (keep broken). |
Полный список всех поддерживаемых опций можно получить, выполнив:
Создание RAR архивов в Linux
Для создания RAR архивов в Linux используется пакет RAR.
Установка пакета RAR
Для установки RAR выполните команду (выберите соответствующую команду для вашего дистрибутива):
Создать RAR архив
Для создания RAR архивов используется опция a команды rar . Например, заархивируем директорию mydir в файл archive.rar :
В результате будет создан архив archive.rar , который содержит только файлы, расположенные непосредственно в директории mydir , не включая вложенные директории.
Чтобы заархивировать директорию полностью, включая все вложенные файлы и директории, используется опция -r (recursive):
Можно указать список файлов, которые нужно заархивировать:
Указать степень сжатия
Чтобы указать степень сжатия, используется опция -mЧИСЛО , для которой указывается число от 0 до 5. 0 — без сжатия, 1 — минимальное сжатие, 5 — максимальное. По умолчанию используется степень сжатия — 3. Пример создания архива с максимальной степенью сжатия:
Разбить архив на несколько файлов
Используя опцию -vРАЗМЕР можно создать архив, который будет разбит на несколько файлов. Для указания размера нужно использовать обозначения: M — мегабайты, k — килобайты, b — байты. Например, создадим архив, который разобьем на файлы размером 100 мегабайт:
Распаковать такой архив можно обычными средствами команды rar . Только в качестве архива нужно указать первый файл: rar x archive.part01.rar
Добавить файлы в архив
Чтобы добавить файлы в существующий архив, используется опция u :
Удалить файлы из архива
Rar позволяет удалять отдельные файлы из существующего архива, для этого используется опция d .
Восстановить битый архив
Если архив поврежден, то можно попытаться его восстановить, используя опцию r :
Создать архив с паролем
Чтобы создать архив, защищенный паролем, используется опция -p :
Для существующего RAR-архива также можно задать пароль:
В результате выполнения данной команды появится запрос на ввод пароля.
Распаковать архив
Команда rar , как и описанная выше команда unrar , умеет распаковывать архивы. Для распаковки архивов используется опция x :
Другие возможности команды RAR
Команда rar обладает внушительным количеством опций. Полное описание команды rar можно получить, выполнив в терминале:
Источник