LINUX.ORG.RU

Заделал пару функций.

 ,


1

2

Пока летел в самолете, наваял для bashrc парочку функций. Выложил все в github. https://github.com/mrAibo/bash/tree/main

В общем-то ничего особенного, за исключением пары функций из-за которых и выкладываю. Может кто-то оценит. Документацию составил ИИ. Тестируйте, если есть идеи, что добавить/улучшить - пишите. Будет время рассмотрю.

rcp (Remote Copy) Function

The rcp function is a versatile tool for copying files and directories, both locally and to/from remote systems. It supports both rsync and scp, offering various options for compression, moving files, and more.

Usage

rcp [OPTIONS] source destination

Key Features

  • Supports both local and remote file transfers
  • Option to use rsync (default) or scp
  • File compression during transfer
  • Move files instead of copying
  • Bandwidth limiting
  • Exclude patterns for selective file transfer
  • Verbose output option

Options

  • -z, --compress: Compress data during transfer
  • -m, --move: Move files (delete source after successful transfer)
  • -u, --user USERNAME: Specify remote username
  • -p, --port PORT: Specify SSH port
  • -i, --identity FILE: Use specific SSH identity file
  • -l, --limit RATE: Set bandwidth limit (KB/s, rsync only)
  • -e, --exclude FILE: Specify exclude file or pattern
  • -s, --use-scp: Force SCP instead of rsync
  • -v, --verbose: Enable verbose output
  • -h, --help: Show help message

Examples

  1. Basic copy:

    rcp /path/to/source user@remote:/path/to/destination
    
  2. Compressed transfer with verbose output:

    rcp --compress --verbose /path/to/source user@remote:/path/to/destination
    
  3. Move files using a specific SSH key and port:

    rcp -m -p 2222 -i ~/.ssh/my_key /path/to/source user@remote:/path/to/destination
    
  4. Use SCP with exclude patterns:

    rcp --use-scp --exclude '*.log' /path/to/source user@remote:/path/to/destination
    
  5. Limit bandwidth and use compression:

    rcp -z -l 1000 -e '**/*.tmp' /path/to/source user@remote:/path/to/destination
    

This function provides a flexible and powerful way to handle file transfers in various scenarios, combining the strengths of rsync and scp with additional features for improved usability.

ex (Extract and Compress) Function

The ex function is a versatile tool for extracting and compressing various types of archive files. It supports multiple formats and offers options for both extraction and compression operations.

Usage

ex [OPTIONS] file1 [file2 ...]

Key Features

  • Supports multiple archive formats (e.g., tar.gz, zip, 7z)
  • Can extract and compress files
  • Allows specifying a target directory for operations
  • Option to delete original files after successful operation
  • Supports excluding files/directories during compression
  • Verbose mode for detailed operation information

Options

  • -x, --extract: Extract mode (default)
  • -c, --compress FORMAT: Compress mode (specify format: tar.gz, tar.bz2, zip, 7z)
  • -v, --verbose: Enable verbose output
  • -t, --target DIR: Specify target directory for extraction or compression
  • -d, --delete: Delete original file(s) after operation
  • -e, --exclude PATTERN: Exclude files/directories matching the pattern or specified in a file
  • -h, --help: Show help message

Supported Formats

Extraction

  • .tar.bz2, .tar.gz, .bz2, .rar, .gz, .tar, .tbz2, .tgz, .zip, .Z, .7z, .xz, .exe, .tar.xz, .tar.zst

Compression

  • tar.gz, tar.bz2, zip, 7z

Examples

  1. Extract an archive:

    ex archive.tar.gz
    
  2. Compress files to a zip archive with verbose output:

    ex --compress zip --verbose --target /tmp file1 file2
    
  3. Extract files to a specific directory and delete the original archive:

    ex --extract --delete --target /path/to/extract archive.zip
    
  4. Compress directories to a tar.gz archive, excluding certain files:

    ex --compress tar.gz --exclude '*.log' --target /tmp dir1 dir2
    
  5. Compress using patterns from an exclude file:

    ex -c zip --exclude exclude.txt dir1 dir2
    

The ex function simplifies the process of working with archives by providing a unified interface for both extraction and compression tasks. It supports a wide range of formats and offers flexibility through various options, making it a powerful tool for file archiving and extraction operations.

duu (Enhanced Disk Usage) Function

The duu function is an enhanced version of the standard du (disk usage) command. It provides a colorful, easy-to-read summary of disk usage for directories and files.

Usage

duu [directory]

If no directory is specified, it will analyze the current directory.

Key Features

  • Color-coded output for easy reading
  • Sorts results by size in descending order
  • Displays sizes in human-readable format (K, M, G, T)
  • Shows percentage and graphical representation of disk usage
  • Summarizes total disk usage at the end

Output Format

The function displays the following information:

  1. Size: The amount of disk space used
  2. Unit: The unit of measurement (K, M, G, T)
  3. Usage: A graphical bar representing the percentage of usage
  4. Path: The file or directory path

Color Coding

  • Green: Kilobytes (K)
  • Yellow: Megabytes (M)
  • Cyan: Gigabytes (G)
  • Magenta: Terabytes (T)
  • Blue: Default color for other units

Example Output

  Disk Usage Summary  
Size       Unit   Usage    Path
---------- ------ --------- --------------------
   1.23    G      █████░░░░ /home/user/Documents
   856.45  M      ████░░░░░ /home/user/Downloads
   234.56  M      ██░░░░░░░ /home/user/Pictures
   45.67   M      █░░░░░░░░ /home/user/.config
----------------------------------------
Total:     2.34   G     

Benefits

  1. Visual Representation: The bar chart provides an immediate visual cue about the relative sizes of directories.
  2. Color-Coding: Different colors for different size units make it easy to quickly identify large consumers of disk space.
  3. Sorted Output: Results are sorted by size, placing the largest items at the top.
  4. Human-Readable: Sizes are converted to the most appropriate unit (K, M, G, T) for easy understanding.
  5. Total Summary: Provides a total at the end, giving an overview of the analyzed directory’s total size.

Use Cases

  • Quickly identify large files or directories consuming disk space
  • Analyze disk usage patterns in a visually appealing manner
  • Get a summarized view of disk usage in a specific directory

The duu function enhances the standard disk usage analysis by providing a more user-friendly and informative output, making it easier to understand and manage disk space usage.


Use Cases

Quickly identify large files or directories consuming disk space
Analyze disk usage patterns in a visually appealing manner
Get a summarized view of disk usage in a specific directory

qdirstat

/thread

PS летайте самолётами ерофлота

mrjaggers
()

Мда.

$ ./rcp.bash --verbose --use-scp rcp.bash user@127.0.0.1:~
Command: scp -r rcp.bash user@127.0.0.1:~
Transferring rcp.bash to user@127.0.0.1:~...
scp: stat local "rcp.bash/": Not a directory
Transfer failed.

$ scp -r rcp.bash user@127.0.0.1:~
rcp.bash

Ну и зачем ты пути портишь?

Ja-Ja-Hey-Ho ★★★★★
()
$ duu --help

  Disk Usage Summary  
Size       Unit   Usage    Path
---------- ------ --------- --------------------
      0.00 M      ░░░░░░░░░ имена
      0.00 M      ░░░░░░░░░ указанный
      0.00 M      ░░░░░░░░░ интерпретируется
      0.00 M      ░░░░░░░░░ место;
      0.00 M      ░░░░░░░░░ POSIXLY_CORRECT).
      0.00 M      ░░░░░░░░░ --summarize
      0.00 M      ░░░░░░░░░ использование
      0.00 M      ░░░░░░░░░ справки
      0.00 M      ░░░░░░░░░ ввода
      0.00 M      ░░░░░░░░░ 
      0.00 K      ░░░░░░░░░ sparse)
      0.00 M      ░░░░░░░░░ документация:
      0.00 M      ░░░░░░░░░ значения
      0.00 M      ░░░░░░░░░ ошибках
      0.00 K      ░░░░░░░░░ 1K
      0.00 M      ░░░░░░░░░ иногда
      0.00 M      ░░░░░░░░░ перечислены
      0.00 M      ░░░░░░░░░ блоков
      0.00 M      ░░░░░░░░░ 
      0.00 M      ░░░░░░░░░ du
      0.00 M      ░░░░░░░░░ переменных
      0.00 M      ░░░░░░░░░ единицей
      0.00 M      ░░░░░░░░░ доступная
      0.00 M      ░░░░░░░░░ du
      0.00 M      ░░░░░░░░░ ФАЙЛа
      0.00 M      ░░░░░░░░░ atime,
      0.00 M      ░░░░░░░░░ --max-depth=0
      0.00 M      ░░░░░░░░░ это
      0.00 M      ░░░░░░░░░ Ф
      0.00 M      ░░░░░░░░░ --all)
      0.00 M      ░░░░░░░░░ каталоге
      0.00 M      ░░░░░░░░░ если
      0.00 M      ░░░░░░░░░ обязательные
      0.00 M      ░░░░░░░░░ не
      0.00 M      ░░░░░░░░░ не
      0.00 K      ░░░░░░░░░ --one-file-system
      0.00 K      ░░░░░░░░░ --exclude-from=ФАЙЛ
      0.00 K      ░░░░░░░░░ показать
      0.00 M      ░░░░░░░░░ are
      0.00 K      ░░░░░░░░░ --threshold=РАЗМЕР
      0.00 K      ░░░░░░░░░ показывать
      0.00 K      ░░░░░░░░░ показывать
      0.00 K      ░░░░░░░░░ показывать
      0.00 M      ░░░░░░░░░ SIZE
      0.00 K      ░░░░░░░░░ --summarize
      0.00 K      ░░░░░░░░░ --separate-dirs
      0.00 K      ░░░░░░░░░ как
      0.00 K      ░░░░░░░░░ --no-dereference
      0.00 K      ░░░░░░░░░ синоним
      0.00 K      ░░░░░░░░░ --dereference
      0.00 K      ░░░░░░░░░ --count-links
      0.00 K      ░░░░░░░░░ синоним
      0.00 K      ░░░░░░░░░ вывести
      0.00 K      ░░░░░░░░░ эквивалентен
      0.00 K      ░░░░░░░░░ --human-readable
      0.00 K      ░░░░░░░░░ показать
      0.00 M      ░░░░░░░░░ long-iso,
      0.00 K      ░░░░░░░░░ вывести
      0.00 K      ░░░░░░░░░ исключить
      0.00 K      ░░░░░░░░░ --max-depth=N
      0.00 K      ░░░░░░░░░ --dereference-args
      0.00 K      ░░░░░░░░░ --total
      0.00 M      ░░░░░░░░░ выводит
      0.00 M      ░░░░░░░░░ prefixes
      0.00 K      ░░░░░░░░░ --bytes
      0.00 K      ░░░░░░░░░ --block-size=РАЗМЕР
      0.00 K      ░░░░░░░░░ печатать
      0.00 K      ░░░░░░░░░ --all
     -0.00 K      ░░░░░░░░░ --null
      0.00 K      ░░░░░░░░░ 
      0.00 K      ░░░░░░░░░ 
      0.00 K      ░░░░░░░░░ 
      0.00 K      ░░░░░░░░░ 
----------------------------------------
Total:       1.00 G     

😂

Ja-Ja-Hey-Ho ★★★★★
()
Ответ на: комментарий от ripgrep

А если нельзя устанавливать дополнительное ПО? Приходится пользоваться тем, что есть.

CrownRU
() автор топика
Ответ на: комментарий от CrownRU

Судя по коду должно стать лучше.

Вот ещё, например, 1 серьёзная ошибка в swapf:

mv "$1" "$tmp/" && mv "$2" "$1" && mv "$tmp"/* "$2"
rm -rf "$tmp"

Можно попробовать обменять файл с каталогом, но твой скрипт просто удалит файл в первом параметре, т.к. не проверяется exitstatus у mv.

Ja-Ja-Hey-Ho ★★★★★
()
Ответ на: комментарий от mrjaggers

О чем разговор? Я не могу устанавливать левое ПО. Или Вы хотите указать на что-то конкретное?

CrownRU
() автор топика
Ответ на: комментарий от Ja-Ja-Hey-Ho

Ну вот, сейчас вроде swaps должен работать, как задумано. Маленький баг, а сколько кода на исправление…

CrownRU
() автор топика
Ответ на: комментарий от goingUp

Согласен rcp - remote copy не самое лучшее название. Есть идеи как назвать? :) У меня просто rcp, telnet… выпилены изначально.

CrownRU
() автор топика
Ответ на: комментарий от CrownRU

Согласен rcp - remote copy не самое лучшее название. Есть идеи как назвать? :)

чтобы не засирать привычное пространство имён и не огребать конфликтов,

сделать скрипт поверх а свои самоделки уже как его суб-команды.

fu fu@ng utils

fu ex - extract archive

fu xe - create or update (unextract)

fu to - copy TO another

etc etc..

PS/ кстати и нехреновый логотип получился fu@ng

MKuznetsov ★★★★★
()
Последнее исправление: MKuznetsov (всего исправлений: 2)
Ответ на: комментарий от MKuznetsov

Таки удобнее когда команда из одного слова, а не из двух, и желательно покороче. Если ты хочешь внедрять свой софт в какие-то публичные репы - то да, придётся думать про назначение имён, если же для себя - то однозначно надо делать как удобнее - то есть покороче. И не бояться закрывать своими именами что-то системное, если только нет опасности встретить его в чужом скрипте.

firkax ★★★★★
()
Ответ на: комментарий от firkax

Renamed functions: rcp -> rcopy swapf -> flip ex -> pac duu -> dug

CrownRU
() автор топика
Для того чтобы оставить комментарий войдите или зарегистрируйтесь.