Gnu core utilities windows
Coreutils — GNU core utilities
The GNU Core Utilities are the basic file, shell and text manipulation utilities of the GNU operating system. These are the core utilities which are expected to exist on every operating system.
Table of Contents
Getting Help
- Check Questions and Answers for common problems: Coreutils FAQ
- Read the manual locally using info coreutils or see the latest online manual (ж—Ґжњ¬иЄћ).
- The Coreutils Gotchas contains a list of some quirks and unexpected behaviour (which are often mistaken for bugs).
- Search the archives for previous questions and answers:
- General usage and advice: coreutils mailing list.
- Bug reports: bug-coreutils mailing List.
- Send general questions or suggestions to the mailing list at .
- Send translation requests to the language team at the Translation Project.
- Report bugs, including version and distribution variant, to the list at .
Before sending the bug, please consult the FAQ and mailing list archives (above).
Often these perceived bugs are simply due to wrong program usage.
To learn more about reporting bugs, see Getting help with GNU software.
Downloads
Stable source releases are available on the main GNU download server (HTTPS, HTTP, FTP) and its mirrors. Please use a mirror if possible.
Source Code
The latest source with revision history can be browsed using cgit, gitweb or GitHub.
Assuming you have git installed, you can retrieve the latest version with this command:
A Coreutils code structure overview is available, which is useful for educational purposes, or for those interested in contributing changes.
To build from the latest sources please follow the instructions in README-hacking.
Please note that we do not suggest using test versions of Coreutils for production use.
Third Party Testing Resources
Mailing Lists
You do not need to be subscribed in order to post messages to any GNU mailing list. However non-subscribers are moderated by humans so please be patient when waiting for your email to arrive.
You can subscribe to any GNU mailing list via the web as described below. Or you can send an empty mail with a Subject: header line of just “subscribe” to the relevant -request list. For example, to subscribe yourself to the main coreutils list, you would send mail to with no body and a Subject: header line of just “subscribe”.
It has been necessary to moderate the Coreutils mailing lists to prevent the flood of spam. Postings to the lists are held for release by the list moderator. Sometimes the moderators are unavailable for brief periods of time. Please be patient when posting. If you don’t eventually see the message in the list archive then it did not get posted.
The low-volume mailing list coreutils-announce@gnu.org contains all announcements about Coreutils.
Important announcements about Coreutils and most other GNU software are also made on info-gnu@gnu.org.
There are also periodic summaries of committed, rejected and pending changes, to which one can subscribe.
The main discussion list for all things related to coreutils is coreutils@gnu.org. This is a recent change as previously general discussion took place on the bug list. If you have questions, comments, or other general discussion about Coreutils then this is the mailing list for that discussion. If you don’t know where to start then this is the place to start. You can browse and search past postings to the coreutils archive. Discussion prior to its creation in March 2010 is available in the bug mailing list archive.
If you think you have found a bug in Coreutils, then please send as complete a bug report as possible to bug-coreutils@gnu.org, and it will automatically be entered into the Coreutils bug tracker. Before reporting bugs please read the FAQ. A very useful and often referenced guide on how to write bug reports and ask good questions is the document How To Ask Questions The Smart Way. You can browse previous postings and search the bug-coreutils archive.
Trying the latest test release (when available) is always appreciated. Test releases of Coreutils are typically announced on the platform-testers mailing list.
If you would like any new feature to be included in future versions of Coreutils, please send a request to coreutils@gnu.org. This is the general discussion list and a good place to start discussion of a new feature. After consideration you may be asked to log a request into the bug tracker so that the issue is not lost. If you would like to implement yourself, then note that non trivial changes require copyright assignment to the FSF as detailed in the “Copyright Assignment” section of the Coreutils HACKING notes.
Mailing List Etiquette
Please do not send messages encoded as HTML nor encoded as base64 MIME nor included as multiple formats. Please send messages as plain text. Please include a descriptive subject line. If all of the subjects are bug then it is impossible to differentiate them. Please avoid sending large messages, such as log files, system call trace output, and other content resulting in messages over about 40 kB, to the mailing lists without prior contact. Those are best sent directly to those requesting that information after initial contact.
Please remember that development of Coreutils is a volunteer effort, and you can also contribute to its development. For information about contributing to the GNU Project, please read How to help GNU.
Previous Mailing Lists
Previously these utilities were offered as three individual sets of GNU utilities, Fileutils, Shellutils, and Textutils. Those three were combined into the single set of utilities called Coreutils.
Since Coreutils had existed as the three individual packages for a long time you may want to read the archives of those previous mailing lists. Fileutils archive, Shellutils archive, Textutils archive.
Maintainers
Coreutils is currently being maintained by Jim Meyering , PГЎdraig Brady , Bernhard Voelker , Eric Blake , Paul Eggert and Assaf Gordon .
“The Free Software Foundation (FSF) is a nonprofit with a worldwide mission to promote computer user freedom. We defend the rights of all software users.”
Please send general FSF & GNU inquiries to . There are also other ways to contact the FSF. Broken links and other corrections or suggestions can be sent to .
Please see the Translations README for information on coordinating and contributing translations of this article.
Copyright © 2016 Free Software Foundation, Inc.
Gnu core utilities windows
uutils is an attempt at writing universal (as in cross-platform) CLI utilities in Rust. This repository is intended to aggregate GNU coreutils rewrites.
Many GNU, Linux and other utilities are useful, and obviously some effort has been spent in the past to port them to Windows. However, those projects are either old and abandoned, are hosted on CVS (which makes it more difficult for new contributors to contribute to them), are written in platform-specific C, or suffer from other issues.
Rust provides a good, platform-agnostic way of writing systems utilities that are easy to compile anywhere, and this is as good a way as any to try and learn it.
- Rust ( cargo , rustc )
- GNU Make (required to build documentation)
- Sphinx (for documentation)
- gzip (for installing documentation)
uutils follows Rust’s release channels and is tested against stable, beta and nightly. The current oldest supported version of the Rust compiler is 1.32.0 .
On both Windows and Redox, only the nightly version is tested currently.
There are currently two methods to build uutils: GNU Make and Cargo. However, while there may be two methods, both systems are required to build on Unix (only Cargo is required on Windows).
First, for both methods, we need to fetch the repository:
Building uutils using Cargo is easy because the process is the same as for every other Rust program:
Because the above command attempts to build utilities that only work on Unix-like platforms at the moment, to build on Windows, you must do the following:
If you don’t want to build every utility available on your platform into the multicall binary (the Busybox-esque binary), you can also specify which ones you want to build manually. For example:
If you don’t even want to build the multicall binary and would prefer to just build the utilities as individual binaries, that is possible too. For example:
Building using make is a simple process as well.
To simply build all available utilities:
To build all but a few of the available utilities:
To build only a few of the available utilities:
Likewise, installing can simply be done using:
This command will install uutils into Cargo’s bin folder (e.g. $HOME/.cargo/bin ).
To install all available utilities:
To install using sudo switch -E must be used:
To install all but a few of the available utilities:
To install only a few of the available utilities:
To install every program with a prefix (e.g. uu-echo uu-cat):
To install the multicall binary:
Set install parent directory (default value is /usr/local):
The standard package set of NixOS provides this package out of the box since 18.03:
Uninstallation differs depending on how you have installed uutils. If you used Cargo to install, use Cargo to uninstall. If you used GNU Make to install, use Make to uninstall.
To uninstall uutils:
To uninstall all utilities:
To uninstall every program with a set prefix:
To uninstall the multicall binary:
To uninstall from a custom parent directory:
Testing can be done using either Cargo or make .
Just like with building, we follow the standard procedure for testing using Cargo:
By default, cargo test only runs the common programs. To run also platform specific tests, run:
If you would prefer to test a select few utilities:
To simply test all available utilities:
To test all but a few of the available utilities:
To test only a few of the available utilities:
To include tests for unimplemented behavior:
This testing functionality is only available on *nix operating systems and requires make .
To run busybox’s tests for all utilities for which busybox has tests
To run busybox’s tests for a few of the available utilities
To pass an argument like «-v» to the busybox test runtime
To contribute to uutils, please see CONTRIBUTING.
| Done | Semi-Done | To Do |
|---|---|---|
| arch | cp | chcon |
| base32 | expr | csplit |
| base64 | install | dd |
| basename | ls | numfmt |
| cat | more | pr |
| chgrp | od ( —strings and 128-bit data types missing) | runcon |
| chmod | printf | stty |
| chown | sort | |
| chroot | split | |
| cksum | tail | |
| comm | test | |
| cut | date | |
| dircolors | join | |
| dirname | df | |
| du | ||
| echo | ||
| env | ||
| expand | ||
| factor | ||
| false | ||
| fmt | ||
| fold | ||
| groups | ||
| hashsum | ||
| head | ||
| hostid | ||
| hostname | ||
| id | ||
| kill | ||
| link | ||
| ln | ||
| logname | ||
| md5sum (replaced by hashsum) | ||
| sha1sum (replaced by hashsum) | ||
| sha224sum (replaced by hashsum) | ||
| sha256sum (replaced by hashsum) | ||
| sha384sum (replaced by hashsum) | ||
| sha512sum (replaced by hashsum) | ||
| mkdir | ||
| mkfifo | ||
| mknod | ||
| mktemp | ||
| mv | ||
| nice | ||
| nl | ||
| nohup | ||
| nproc | ||
| paste | ||
| pathchk | ||
| pinky | ||
| printenv | ||
| ptx | ||
| pwd | ||
| readlink | ||
| realpath | ||
| relpath | ||
| rm | ||
| rmdir | ||
| seq | ||
| shred | ||
| shuf | ||
| sleep | ||
| stat | ||
| stdbuf | ||
| sum | ||
| sync | ||
| tac | ||
| tee | ||
| timeout | ||
| touch | ||
| tr | ||
| true | ||
| truncate | ||
| tsort | ||
| tty | ||
| uname | ||
| unexpand | ||
| uniq | ||
| unlink | ||
| uptime | ||
| users | ||
| wc | ||
| who | ||
| whoami | ||
| yes |
uutils is licensed under the MIT License — see the LICENSE file for details
About
Cross-platform Rust rewrite of the GNU coreutils
Разбираем исходный код GNU Coreutils: утилита yes
Зачем?
GNU Coreutils
GNU Core Utilites — это набор утилит для выполнения базовых пользовательских операций: создание директории, вывод файла на экран и так далее. По замыслу разработчиков, эти утилиты должны быть доступны в любой операционной системе, что мы и наблюдаем в настоящее время: для Windows есть Cygwin, ну а про *nix и говорить нечего. Сохранить единообразность работы в разных системах помогает стандарт POSIX, который в Coreutils пытаются соблюдать. Coreutils содержит такие часто используемые утилиты, как cat, tail, echo, wc и многие другие.
Для начала выберем самую тривиальную программу под названием yes. Её простота позволит разобраться с используемыми в Coreutils инструментами и библиотеками.
Утилита yes
Как говорится в мане, всё что умеет утилита yes — это бесконечно выводить «yn» в stdout. Если мы передадим yes какие-то аргументы, то вместо «y» yes будет выводить аргументы через пробел. Наверняка похожую программу писал каждый, кто начинал изучать C. А значит у многих есть возможность сравнить свой подход с тем, как это делают суровые бородатые дядьки из GNU. О практическом применении yes немного написано в Википедии.
Исходный код
Переходим к исходному коду. Достать его можно либо с помощью apt-get source и получить версию, которая используется в вашей системе по-умолчанию, либо вытянуть новейшую версию из репозиториев. Мы выберем второй вариант: он более удобен и привычен.
- Coreutils: git clone git://git.sv.gnu.org/coreutils
- Gnulib (заглянем туда пару раз): git clone git://git.savannah.gnu.org/gnulib.git
Исходный код yes умещается в одном файле coreutils/src/yes.c , его и откроем.
Coding style
Первое, на что обращаешь внимание — непривычное форматирование кода. Почитать о нём можно в соответствующей главе GNU Coding Standards. Например, при определении функции тип возвращаемого значения должен располагаться на отдельной строке, как и открывающая скобка:
Для отступов и выравнивания используются только пробелы. Между различными уровнями вложенности разница в отступе составляет 2 пробела. Особо извращённую форму имеют фигурные скобки при операторах:
12 строк
yes.c начинается с обязательного для всех GPL-програм комментария. Он уже успел намозолить мне глаза в других программах и необходимость его наличия была для меня загадкой. Оказывается, что текст этого комментария зафиксирован в инструкции по применению GPL. Именно в ней прописано, что все, кто желает выпускать своё ПО под GPL, должны добавлять эти 12 строк заявления о праве копирования в начало каждого файла исходного кода.
initialize_main
Первое, что делает программа, это вызов initialize_main . Эта функция предназначена для того, чтобы программа выполнила свои специфичные действия над аргументами. На практике, в Coreutils нет ни одной утилиты, которая бы использовала эту функцию для чего-то полезного. Везде используется заглушка, представленная в файле coreutils/src/system.h :
Название программы
В утилитах Coreutils различают два названия программы:
- Официальное название, которое пользователь не может изменить.
- Реальное название исполняемого файла.
Официальное название используется при выводе информации о версии приложения:
Причём это название никак не зависит от имени исполняемого файла:
Такое поведение обеспечивается специально определённым в начале файла макросом PROGRAM_NAME :
Реальное название без всяких хитростей берётся из argv[0] и используется при выводе ошибок и подсказок:
Значение argv[0] помещается в глобальную переменную program_name с помощью вызова функции set_program_name во второй строке main :
Функция set_program_name предоставляется библиотекой Gnulib. Соответствующий код находится в каталоге gnulib/lib/ , в файлах progname.h и progname.c . Интересно заметить, что set_program_name не просто сохраняет значения argv[0] в глобальную переменную program_name , объявленную в progname.h , но и выполняет дополнительные преобразования, связанные с тонкостями использования GNU Libtool, инструмента для разработки динамических библиотек.
Интернационализация
Coreutils используют по всему миру, поэтому во всех утилитах предусмотрена возможность локализации. Причём эта возможность обеспечивается минимальными усилиями благодаря использованию пакета GNU gettext. Немногих удивит использование именно gettext, ведь этот пакет распространился далеко за пределы проекта GNU. Например, интернационализация в моём любимом web-фреймворке Django построена именно на gettext. Про использование gettext совместно с различными языками и фреймворками уже писали на хабре.
Замечательным свойством gettext является то, что он во всех языках используется примерно одинаково, и C не исключение. Здесь есть стандартная магическая функция _ , использование которой можно найти в функции usage :
Определение функции _ находится в уже знакомом нам файле system.h :
Инициализация механизма интернационализации в Coreutils производится вызовом трёх функций в main :
- setlocale устанавливает стандартную локаль окружения в качестве рабочей для приложения
- bindtextdomain говорит, где искать файл с переводами для конкретного домена сообщений
- textdomain устанавливает текущий домен сообщений
Обработка ошибок
Двигаясь дальше по коду main , мы встречаем такую строку:
Интуитивно можно подумать, что в функции close_stdout закрывается стандартный поток вывода, что исключает потерю данных, если мы подменили stdout каким-нибудь файловым дескриптором и используем буферизированный вывод. Но найти исходный код этой функции и понять, что же на самом деле там происходит, выполняются ли какие-нибудь дополнительные действия по подчистке ресурсов, у меня не получилось.
Аргументы командной строки
Это последний вопрос, который не касается работы самой программы. Здесь, как и в случае с интернационализацией, используется проверенное временем и пролезшее во многие проекты (например, в Python) решение — модуль getopt. Этот модуль очень прост: фактически, от разработчика требуется вызывать в цикле одну из функций getopt или getopt_long . Подробнее о getopt можно почитать в интернете, да и на хабре о нём тоже писали.
В Gnulib есть специальная функция parse_long_options для обработки аргументов —version и —help , которые любое GNU-приложение обязано поддерживать. Находится она в файле gnulib/lib/long-options.c и использует getopt_long в своей работе.
Исходный код yes является классным примером работы с getopt. Тут одновременно отсутствует излишняя для обучения сложность с разбором десятков аргументов и присутствует использование всех средств getopt. Сначала, естественно, выполняется вызов parse_long_options . Затем проверяется, что больше никаких опций-ключей не передано и остальные аргументы, если они есть, являются просто произвольными строками:
Следующий код можно перевести на русский так: «Если в списке аргументов командой строки ничего кроме ключей —version и —help не было, то мы будем выводить „y“ в stdout»:
Запись в argv[argc] не является ошибкой: стандарт ANSI C требует, чтобы элемент argv[argc] был нулевым указателем.
Главный цикл
Ну вот мы и добрались до самого функционала программы. Вот он весь, как есть:
Здесь можно отметить, что все действия выполняются внутри условия if , а не в его теле. Значит, Кёрниган и Ритчи не врали, когда писали, что опытный C-программист реализует копирование строк так:
