LINUX.ORG.RU

KOSMOS — сборка комфортненьких shell-скриптов, функций и конфигов системы

 , kosmos, , ,


0

1

После около 13 лет разработки создал репозиторий с проектом KOSMOS.

Это набор очень удобных скриптов и функций (в общей сумме более 200). Их легко и быстро запускать просто вводя короткие названия в терминале.

Удобный механизм запуска и создания новых скриптов. Просто введя 'C newscript' запускается $EDITOR с готовой шапкой #!/bin/bash в котором прописываешь скрипт, после просто сохранения которого можно в любом терминале запустить этот скрипт просто по названию 'newscript' (он сохранился в директории со скриптами и ему прописался x-bit).

Один из моих любимых и полезных скриптов - pk. Это фронтенд для всех тулзов и утилит пакетного менеджера в CRUX, все в одном. Простой запуск pk <что-то там>, включая всё нужное (установка, обновление, сборка и т.д.). pk i <port> - установить, pk u <port> - обновить, pk b <port> - собрать, и т.п. На данный момент 40 функций.

mig - скрипт для миграции конфигов или любых наборов списков файлов из одной системы в другую.

S2R - скрипт для запуска ОС с корнем в tmpfs, можно потом вынуть флешку и пользоваться системой вообще без дисков.

Также там сборка моих конфигов (CRUX GNU/Linux) включая коллекцию портов.

В KOSMOS реализована идея создания корневого конфига (/CONFIG), содержащего основные переменные OS. Можно будет не зависеть от FHS, создавать свою структуру директорий. Кому сдался этот /usr/?

Благодарность всем, кто помогал или принимал участие.

# A collection of usefull open-source shell scripts (bash scripts, tools, functions)
# and configuration files.


The scripts use /CONFIG file which contains main system variables:
BOOT, BIN, CFG, DEV, LIB, PROC, RUN, SYS, TMP, VAR, ...
 Variables with directoty names will be used in future for specifying
 main directories of OS.
 It will not be limited by FHS, not depent on it.
 No need of /usr/. Create own set of tree(s).
kernel, libc, init, system_profile, bootloader, system_ISA, system_CPU, default_SHELL, ...


The scripts:


si  - (system install) source-based package manager (set of tools)
for UNIX-like systems
with automatic 100% correct dependencies resolving.
 Ports system like in CRUX, Gentoo, FreeBSD, NetBSD, OpenBSD.
 Optional cross-architecture toolchain building, which allows 
creating new UNIX-like Operating Systems
(distributions of custom kernels and selected environments,
idealy, ability to choose an open-source kernel
(FreeBSD, Haiku, HURD, L4, Linux, NetBSD, OpenBSD, Plan9 and , ...),
choose from varios libc's,
and choose environments: GNU, or not GNU, *BSD, Plan9 and , ...).
Can create entier new distribution in a directory with one command.
 All the process of building of each package is user customized with set of options.
All configure options of building for each port are listed in special configuration
files and scripts (recipes) of each port.
 Absolutely correct dependency resolving is based on 5 special curtain
CONF*, BUILD*DEPS* and RUN*DEPS* files (arrays ?) of eatch port.
'CONF*' -- list of all configure options.
'BUILD_DEPS*' -- list of all build dependencies.
'RUN_DEPS*' -- list of all run dependencies.
'BUILD_CONF_DEPS*' associative array with list of all configure options that require build dependencies.
'RUN_CONF_DEPS*' associative array with list of all configure options that require run dependencies.
This means that all configure options are connected to curtain dependencies. Also if you add/remove an configure option, it will pick up all required deps.
 There is "$PM_db/FLAGS/$system_ISA/$system_CPU/FLAGS" file (and 'CREATE_FLAGS' script for generating the file,
and 'ED_FLAGS' for editing the file) which contains all CPU-specified 'make' variables 
(ASFLAGS, CPPFLAGS, CFLAGS, CXXFLAGS, LDFLAGS, LDLIBS, MAKEFLAGS, ..., all of them).
 Lists of recipes (files with recipes for proceeding).
 Varios profile sets of recipes (desktop, server, router, ... create any).
 Logging!
 Sandbox for build and installation process. Tool for modifying all proceeded built packages on set of rules.
 Posibility of installing selected ports into any new or existing prefix.
There will be core in / and availability to add or remove ports to 'core'
or to any available prefix. Like prefix in 'Gobo Linux', but name and combination
of prefixes will be user specified.
For example, user can place a whole toolchain (or any set of ports) in a separate directory.
 Existence of CONF file that specifies all build options for each port gives an ability to
add in future optionall USE_FLAG system (like in 'Gentoo') for any set of ports.
Even MULTI-FLAGS.
Spectre of available/used use-flags will be user specified.
 User controlls the process of building every port with recipes and configuration files,
which give an ability to control every configure option of build process of each port.
User can be a maintainer of his own system.
 User has full control over the operating system.
#### 'si' is not yet completed. I use 'pk' on my CRUX system.


pk - script for package management in CRUX OS with prompt waiting for confirmation,
showing in color which packages will be updated, installed or removed.
It uses a simple syntax, like:
'pk i package1 ...' -- for installing package(s) with all dependencies,
'pk u pakage1 package2' -- for updating packages, or just
'pk u' -- for updating all available.
 It implements many PM features (build (b), download (do), install, install with deps (i), update,
update with new deps (u), update prt-get cache (c), search (s), search in description (sd),
show missing deps (m), show deps (de), show packages that depend on (depson),
check signature (cs), update signature (us), and other).
 It is like a custom front-end for pkgutils, prt-get, prt-utils, pkg-backup, ... .
 'pk' is my (temporary) pakage manager, it is an attemp to make package management
in my favourite and one of the bests disto, CRUX, more nice, until 'si' and my
recipes (ports) collection will be completed.
'si' will be able to do all that 'pk' can and beyond.
Probably, 'pk' will be a symlink to 'si', or even 'si' will be renamed to 'pk'.


chain - creates a toolchain with a single command (amd64 only for now), based on LFS Book.
It also installs CRUX PM, which allows building CRUX from scratch.


S2R  - (System to RAM) move / to tmpfs and make operating system to work completely from RAM
without need of any attached disks or flash-drives.


C  - create/modify scripts. For example 
'C myscript' will create 'myscript' with an "$EDITOR" in "$KOSMOS_scripts/" directory,
after saving the file, you can run it immidiately just typing 'myscript' in any terminal.


ch  - chroot with automatic mounting.


d  - better cd.


GET_OPTS / GET_ARGS  - get options (starting with '-' or '+') / non-options from "$@".
Extended options with an argument like '-d1' or '-d 1' may be defined by EOPTS='-d'.
For extended options, argument of which may not start with '-' (optional positive argument),
use $PEOPTS.
If there is an option like '-and' (single option, but not starting with --),
SOPTS='-and' shoud be used.
$EOPTS, $PEOPTS, $SOPTS are space separated lists, like EOPTS='-d -f -N'.
If you want to catch options starting with '+', use plus_options=1.
 In script running 'GET_ARGS "$@"; GET_OPTS "$@"' will create arrays 'ARGS' and 'OPTS',
containing all arguments.
# Should create 'GET_ARGUMENTS' function, which will create some kind of an associative array 'ARGUMENTS' with all arguments and options in one.


g  - 'grep -IP[r]' - automatic '-r' when needed. And similar links (gi, gv, gc, gL, gl, giL, gil, ...)
for specific keys.


U  - unplug device.
Sync FS-cache, disable swaps, recursive unmount, flush HW-cache on block device.
For example 'U sdb' will unplug "$DEV/sdb" device.


u  - recursive unmount.


x  - extract an archive. For example 'x KOSMOS.txz' or 'x files.xz'.


T  - create tar archive. For example 'T archive.txz files/'.


gin  - install GRUB2 and automaticaly modify PARTUUID in 'fstab' and 'grub.cfg'.


mig - migrate (configuration) files from one system (dir) to another.
For example 'mig / /new_system/' will copy set of (config) files to '/new_system/'.
A key '-l' sets a set of rules for migration, for example '-l config'; you can
create own set of actions.


s  - sync SW & HW disks caches.


b / bb  - show processes.


And more than hundred other scripts and functions...

ССЫЛКА НА ХРАНИЛИЩЕ КОДА

Перемещено CrX из opensource

★★★★★

Последнее исправление: teod0r (всего исправлений: 8)

Не… На новость для главной явно не тянет, извини.

Подобного добра у каждого второго линуксоида полный ~/.local/bin. У кого чуть поменьше, а у кого и побольше. Что поделился — хорошо в целом, но до новости не дотягивает.


P.S. Зачем такой изврат:

Целый bash ещё один запускать ради этого… Не проще так?

alias l="ls --group-directories-first -AlpQv"
alias lh="l -h"
alias lk="l -d"
alias kl="lk"

И не парить мозг…

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

Там не пароль а сессия, её надо было сбрасывать. Она сбрасывается от сброса пароля? Возможно она вообще просроченная кстати.

А вдруг он не сможет пароль восстановить?

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

Там не пароль а сессия, её надо было сбрасывать

Я знаю, я бы так и сделал, если бы мог, но такой кнопки у модераторов нет. (@maxcom, может быть хорошей идеей добавить для таких случаев)

Она сбрасывается от сброса пароля?

Да.

А вдруг он не сможет пароль восстановить?

Сможет ;)

upd: видишь, смог :)

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

Не проще так?
alias
И не парить мозг…

проще, но не универсально. из скрипта например алиасы не запустишь. и они сильно ограничены по тому что можно в них закодить.

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

из скрипта например алиасы не запустишь.

Зачем тебе в скрипте эти сокращения? Экономия на двух байтах в самом скрипте, но с вызовом ещё одного скрипта, запускающего цельный bash? Они же на то и сокращения, что нужны только в интерактивной сессии. Ну и если сильно надо, можно же . aliases.sh.

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

Так в том и суть, что ты тут ничего такого и не закодил. Просто усложнение ради усложнения.

CrX ★★★★★
()
Последнее исправление: CrX (всего исправлений: 1)

зато я узнал что есть git.org.ru, но так и не понял кто все эти люди и где собственно размещён репозиторий, кто в ответе.

Ровно так-же не понял пользователей сервиса - там в About про то как скачать/установить софт, а не про сервис.

MKuznetsov ★★★★★
()

Ну и зачем?

По опыту: чужие скрипты, алиасы, конфиги, очень редко заходят. Да даже свои.

Спустя десятилетия начинаешь понимать, что ничуть не сложно написать ls вместо l, ls -l вместо ll, и т.д. и т.п. Не умрёшь от нажатия 2-3 лишних клавиш, зато не будешь путаться на чужих серверах.

А когда начинаются скрипты и алиасы для более сложных вещей, то через 2-4 недели уже сам забываешь, что и зачем писал.

Я давно начал сводить скрпиты и алиасы к минимуму. Только если замечаю, что раз 20 делал одно и то же, и это можно легко и быстро автоматизировать.

И вместо алиасов давно предпочитаю аббревиатуры fish (abbr): не надо помнить, во что оно раскроется, т.к. оно раскрывается сразу же после набора, и, к тому же, может раскрываться в любом месте командной строки (можно писать аббревиатуры, раскрывающиеся в | less -R, и т.д.).

Chiffchaff
()
Последнее исправление: Chiffchaff (всего исправлений: 1)
Ответ на: комментарий от antonio-an

что это и для чего?

коллекция разных скриптов +функций для удобного сидения в терминале.
не нравится набирать 'grep -IPors'? набирай просто g
pk более удобный ПМ для CRUX.
ch - это chroot с автоматическим монтированием /proc, /sys, /dev. просто ch /dir

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

не нравится набирать ‘grep -IPors’? набирай просто g

Если требуется часто искать, то лучше сразу установить и использовать ripgrep, в котором разумные установки по умолчанию (типа рекурсивного поиска). Заодно ещё куча опций, делающих гораздо более удобным инструментом, нежели ванильный grep.

Chiffchaff
()
Ответ на: комментарий от CrX

Не… На новость для главной явно не тянет, извини.

а чё нет? хотя бы мини. может, в описании что подкорректировать, добавить? номер версии добавить? я решил перейти на нумерацию типа 20260319, до этого была версия 0.0.87.

teod0r ★★★★★
() автор топика
Последнее исправление: teod0r (всего исправлений: 1)