Разделы можно пропускать без ущерба для понимания, ровно как и любые непонятные/неинтересные места в них.
Перенаправления
Как обычно:
echo foo > bar
echo foo 2> bar
echo foo > bar 2>&1
cat
Да, в Windows есть аналог многоликой команды cat, которая является одной из команд, выражающих суть UNIX’а. Это команда type. Она принимает один или несколько аргументов — имена файлов.
type file
Если нужно, чтоб type читал с экрана (например, если нужно создать файл, на лету наполнив его содержимым), то нужно набрать
type con > file
con — это аналог /dev/tty
(подробнее об этом в следующем разделе).
То есть вышеприведённая команда является аналогом UNIX’овой команды cat /dev/tty > file
или cat - > file
или просто cat > file
.
Когда вы закончите набирать файл, нажмите на новой строке Ctrl-Z и Enter. Это признак конца файла, аналог Ctrl-D в UNIX’е.
Сейчас будет куча технических подробностей про Ctrl-D и Ctrl-Z, их можно пропустить и перейти к следующему разделу.
В UNIX’е, когда юзер нажимает Ctrl-D, эта комбинация не обрабатывается самим приложением (например, в GNU/Linux в tty1 она обрабатывается ядром, если включен CONFIG_VT [на сегодняшний день (2012) CONFIG_VT включен по дефолту на десктопе, хотя есть планы по её выкидыванию]). А запущенное приложение получает EOF (End Of File, конец файла) в чистом виде (а не саму комбинацию клавиш или символ Ctrl-D). То есть как если бы ввод просто закончился. Иными словами, getchar в приложении возвращает EOF, а read — 0.
В Windows то же самое, Ctrl-Z и Enter заставляют getchar вернуть EOF.
/dev/null, /dev/tty и т. д.
Аналог /dev/null
— это устройство nul. Причём оно как бы присутствует в каждой папке. Это тянется со времён старых версий DOS’а, когда не было папок.
Теперь о других устройствах. Аналог /dev/tty
— это con, от слова console. Причём con — это аналог именно /dev/tty
, а не /dev/console
, так как в Windows у каждого окна командной строки con свой.
Аналоги /dev/ttyS0
, /dev/ttyS1
, /dev/ttyS2
, /dev/ttyS3
— это com1, com2, com3, com4 (но винде есть ещё com5 и т. д.). Это устройства serial console, они же COM-порты, они же последовательные порты.
Обычными средствами винды нельзя создать файл или папку с именем con или nul и т. д. Но можно исхитриться: mkdir \\.\c:\con
.
Есть шуточная версия того, почему в Windows трудно создать файл с именем con. А именно: у Билла Гейтса было прозвище con, то есть ботаник. Подробнее см., например, здесь: vk.com/wall-31439745_2474 (естественно, этой информации нельзя доверять).
Подробнее про эти устройства тут: en.wikipedia.org/wiki/Device_file#MS-DOS.
/dev, /dev/sda1, …
После прочтения предыдущего раздела у вас мог возникнуть вопрос: и что, всё? /dev/null
, /dev/tty
и ещё несколько штук девайсов? А где /dev/sda1
и прочие бесчисленные устройства? Ведь в GNU/Linux’е папка /dev может содержать сотни устройств!
Ответ таков: да, в Windows есть целая папка с такими устройствами. Это \Device
. Её сложно посмотреть через обычный пользовательский интерфейс. Там лежат устройства типа \Device\HarddiskVolume1
— это аналог GNU/Linux’ового /dev/sda1
.
Эти устройства появились в NT-шных версиях Windows’а и не тянутся с DOS’овых времён, в отличие от устройств из предыдущего раздела.
Пайпы, они же конвееры
cmd1 | cmd2
, так же, как и в UNIX.
/etc/fstab
Его аналог — это ветка HKEY_LOCAL_MACHINE\SYSTEM\MountedDevices
в реестре Windows (да, да, в винде, как и в UNIX, есть понятие монтирования). Кстати, если у вас до этого были проблемы с переносом установленного Windows’а с одного раздела на другой, или с переименованием дисков в Windows’е или с чем-то ещё подобным, то — вот оно, решение!
Сейчас будет рассказ для тех, кто задумал перенести винду с одного раздела на другой. Остальные могут его пропустить и перейти к следующему разделу.
Если, скажем, вы перенесли Windows с одного раздела на другой, то после этого нужно сделать два шага: разобраться с загрузчиком и его конфигами (об этом в следующем разделе) и подредактировать этот самый ключ реестра (в общем-то так же, как и в GNU/Linux’е: GRUB + fstab). Если ключ не подредактировать, то винда загрузиться не сможет, так начнёт грузиться с нового раздела (то есть того, на который мы копирнули винду), а продолжит — со старого (то есть того, с которого мы копирнули винду). Все системные вещи будут загружены с нового, а всякие Касперские — со старого. Итак, нужно удалить из этой ветки все записи, кроме записи «(По умолчанию)». Тогда винда забудет всё, что знала о разделах и при следующем запуске будет считать своим разделом тот, с которого запустилась (что нам и надо). Короче говоря, автоматически определит разделы.
Правда, тут возникает вопрос: а как подредактировать реестр какой-нибудь винды, не загружаясь в неё? Хм, я для этого использовал Windows PE, который входил в комплект пиратской сборки винды, поэтому я подробности рассказывать не буду. (См. другие способы в этой ветке: geektimes.ru/post/156749/#comment_5355987 от EndUser.)
Ещё несколько вариантов:
- Почистить реестр, выключить компьютер (можно «жёстко»), а потом копирнуть винду. Однако, я это не проверял. Не факт, что винда даст вам отредактировать этот ключ реестра и что она не заполнит его снова при выключении
- Отредактировать реестр, и сразу же, не выключая комп, копирнуть запущенную винду на другой раздел. Но и это тоже не проверялось
- Если вы копируете винду с одного физического диска на другой, можно после копирования вынуть из компьютера старый физический диск и загрузиться в новый хотя бы один раз (чтоб винда обновила MountedDevices). Потом можно вставить старый диск обратно. Такой же трюк можно проделать даже с разделами на одном физическом диске: просто временно удалить старый раздел, а потом восстановить его обратно (ясно, что делать это нужно крайне осторожно). Ну и конечно же, всё это не проверялось :))
- Смонтировать реестр Windows в GNU/Linux как winregfs
И наконец: использовать разные программы для копирования/бекапов разделов (типа Acronis) бесполезно: все они не меняют реестр (скорее всего), поэтому работать в такой ситуации (копирование винды в пределах одного компа) не будут.
И ещё: весь материал этого раздела проверялся только на Windows XP.
/boot/grub/grub.cfg
В Windows XP его аналог — это файл boot.ini в корне раздела с Windows, а в Windows 7 — это Windows Boot Manager.
Мощный командный интерпретатор
В стандартном интерпретаторе (то есть в cmd.exe) есть много разных фич типа ветвления, так же, как и в UNIX’овых интерпретаторах. Там даже есть дебаговый вывод (а-ля set -x
), а именно echo on
, правда он включен по дефолту и обычно первым действием в скрипте его отключают (echo off
, разумеется).
Вообще, виндовая команда echo крайне непоследовательна: её действие довольно странным образом зависит от аргумента:
cmd.exe | bash |
---|---|
echo foo | echo foo |
echo on | set -x |
echo off | set +x |
echo | shopt -o xtrace |
После лицезрения этой таблицы все юниксоиды, конечно же, схватились за голову и сказали: «Что за идиоты проектировали винду?» Впрочем, в UNIX’е тоже не всё гладко: с какой стати set -x
включает дебаг, а set +x
выключает его??? То же самое относится к остальным режимам, включаемым командой set.
Ах да, я же обещал мощный командный интерпретатор. cmd.exe таковым, конечно же, не является. А вот PowerShell — является. Одной из особенностей PowerShell’а является то, что он «понимает» обычные UNIX’овые команды, например, ls. Правда, на самом деле эта команда похожа на UNIX’овую лишь своим названием и идеей, опции у этого ls всё равно совсем другие. ls — это всего лишь один из алиасов на Get-ChildItem. А ещё в винде есть полноценный IDE для написания PowerShell-скриптов с визуальным отладчиком! Вы можете себе такое представить в UNIX’е? Да, есть конечно bashdb, но визуальный отладчик, конечно же, удобнее.
Спасибо Evgeny_Shiryaev, 6opoDuJIo, amdf, easyman, EndUser, risik, NoOne и aik за ценные замечания и исправления ошибок.
Where is the Windows equivalent of /dev/null? 🗑️
You may have noticed that your tech-savvy friends who use operating systems like Linux or macOS often mention something called «/dev/null.» It may sound like a mysterious place, but it’s actually a special file in the Unix-like systems that acts as a black hole for data. So, what about Windows? Is there an equivalent to /dev/null?
Understanding /dev/null
Before we delve into the Windows world, let’s quickly understand what /dev/null does. In Unix-like systems, everything is a file, including devices. /dev/null is a special file that discards any data written to it and produces no output when read from. It’s like a virtual trash can where you can dispose of unwanted data.
The Windows Equivalent — NUL
Now, let’s move on to Windows. While Windows does not have an exact equivalent to /dev/null, it does have something similar called «NUL.» NUL is a reserved name that represents a device file that discards everything written to it. Just like /dev/null, writing to NUL in Windows silently discards the data, and reading from it will always give you an end-of-file (EOF) character.
Using NUL in Windows
To leverage the power of NUL and replicate the functionality of /dev/null in Windows, you can use it in various scenarios. Here are a few examples:
Output Suppression:
If you want to run a command but don’t want to see the output, you can redirect it to NUL. Let’s assume you’re running a command called some-command
:
some-command > NUL
This command will run some-command
and discard the output, keeping your console clean and clutter-free.
Disabling Program Output:
If you’re running a program that has verbose output, but you want to disable it, simply redirect the output to NUL:
program-with-verbose-output.exe > NUL
This will run the program without showing any output on the console.
Discarding Log Files:
If you want to ignore or discard log files generated by an application, you can redirect them to NUL. Here’s an example with the log.txt
file:
rename log.txt NUL
This command renames log.txt
to NUL, effectively discarding the log file.
Conclusion
While Windows does not have an exact equivalent to /dev/null, the «NUL» device in Windows serves a similar purpose. It allows you to discard data, suppress output, and disable program verbosity. The next time you encounter a situation where you need a black hole for your data in Windows, think of «NUL.»
So, embrace the Windows way of discarding data with its own virtual trash can, and make use of NUL. 💥
Remember, if you found this tip useful, don’t forget to share it with your tech-savvy friends so they can unleash the power of NUL too! 😄
From Wikipedia, the free encyclopedia
In some operating systems, the null device is a device file that discards all data written to it but reports that the write operation succeeded. This device is called /dev/null
on Unix and Unix-like systems, NUL:
(see TOPS-20) or NUL
on CP/M and DOS (internally \DEV\NUL
), nul
on OS/2 and newer Windows systems[1] (internally \Device\Null
on Windows NT), NIL:
on Amiga operating systems,[2] and NL:
on OpenVMS.[3] In Windows Powershell, the equivalent is $null
.[4] It provides no data to any process that reads from it, yielding EOF immediately.[5] In IBM operating systems DOS/360 and successors[a] and also in OS/360 and successors[b] such files would be assigned in JCL to DD DUMMY
.
In programmer jargon, especially Unix jargon, it may also be called the bit bucket[6] or black hole.
/dev/null is described as an empty regular file in Version 4 Unix.[7]
The Version 5 Unix manual describes a /dev/null device with modern semantics.[8]
The null device is typically used for disposing of unwanted output streams of a process, or as a convenient empty file for input streams. This is usually done by redirection. For example, tar -c -f /dev/null "example directory"
can be used to dry-run the TAR file archiving utility to see if any errors would occur but without writing any file.
The /dev/null
device is a special file, not a directory, so one cannot move a whole file or directory into it with the Unix mv
command.
References in computer culture
[edit]
This entity is a common inspiration for technical jargon expressions and metaphors by Unix programmers, e.g. «please send complaints to /dev/null
«, «my mail got archived in /dev/null
«, and «redirect to /dev/null
«—being jocular ways of saying, respectively: «don’t bother sending complaints», «my mail was deleted», and «go away». The iPhone Dev Team commonly uses the phrase «send donations to /dev/null
«, meaning they do not accept donations.[9] The fictitious person name «Dave (or Devin) Null» is sometimes similarly used (e.g., «send complaints to Dave Null»).[10] In 1996, Dev Null was an animated virtual reality character created by Leo Laporte for MSNBC’s computer and technology TV series The Site. Dev/null is also the name of a vampire hacker in the computer game Vampire: The Masquerade – Redemption. A 2002 advertisement for the Titanium PowerBook G4 reads «Sends other UNIX boxes to /dev/null.»[11]
The null device is also a favorite subject of technical jokes,[12] such as warning users that the system’s /dev/null
is already 98% full. The 1995 April Fool’s issue of the German magazine c’t reported on an enhanced /dev/null
chip that would efficiently dispose of the incoming data by converting it to a flicker on an internal glowing LED.
Dev/Null is also the name of an electronic dance music producer and jungle DJ.[13]
- /dev/full
- /dev/zero
- Device file
- Filesystem Hierarchy Standard
- Memory hole
- rm (Unix)
- Standard streams
- Unix philosophy
- Write-only memory
- ^ The most recent being z/VSE.
- ^ The most recent being z/OS.
- ^ «Redirecting Error Messages from Command Prompt: STDERR/STDOUT». support.microsoft.com. Retrieved 2020-03-06.
- ^ Commodore-Amiga, Inc. (1986). The AmigaDOS Manual. Bantam Books. p. 12. ISBN 0-553-34294-0.
- ^ «OpenVMS Programming Concepts Manual». h30266.www3.hpe.com. Archived from the original on 2020-07-02. Retrieved 2020-03-06.
- ^ SteveL-MSFT. «about_Automatic_Variables — PowerShell». docs.microsoft.com. Retrieved 2020-03-06.
- ^ «Single Unix Specification Section 10.1: Directory Structure and Files». The Open Group. Retrieved 2012-11-29.
- ^ «bit bucket». Jargon File. Retrieved 2013-12-27.
- ^ Thompson, K.; Ritchie, D. M. (November 1973). UNIX Programmer’s Manual, Fourth Edition. Bell Telephone Laboratories, Inc. sh (I) (./man1/sh.1). Online at TUHS.
- ^ Thompson, K.; Ritchie, D. M. (June 1974). UNIX Programmer’s Manual, Fifth Edition (PDF). Bell Telephone Laboratories, Incorporated. mem (IV).
- ^ «Dev-Team Blog — Donations to /dev/null». 2015-09-07. Archived from the original on 2015-09-07. Retrieved 2018-11-15.
- ^ Goodman, Danny (2004). Spam Wars: Our Last Best Chance to Defeat Spammers, Scammers, and Hackers. New York: SelectBooks. p. 170. ISBN 9781590790632. OCLC 1036874851.
- ^ «Image: unixad.jpg, (1094 × 720 px)». Archived from the original on 2013-03-26. Retrieved 2015-09-02.
- ^ «The FreeBSD Funnies». Freebsd.org. Retrieved 2012-11-28.
- ^ «Dev Null Microjunglizm». The New Yorker. Retrieved 2024-01-24.
- /dev/zero equivalent in windows?
- /dev/zero equivalent in windows? – Server Fault
- /dev/zero
- Is there a /dev/null on Windows?
- / dev / zero echivalent în Windows?
- / dev / zero ekvivalent v systému Windows?
/dev/zero equivalent in windows?
Download "dd for Windows" and open Windows Command-line ("cmd.exe").
Type: "cd /D [directory]" to the "dd" folder.
Type: "dd --list" to show list of Volumes, Disks, and Partitions. Locate your device.
Type: "dd if=/dev/zero of=\\?\Device\Harddisk1\Partition0 --progress"
Choose between "/dev/zero" and "/dev/random" as the write operation. Ensure you select your device based on step 3.
Wait for the zero or random write process to complete and then run hexdump to display hexadecimal value, which should read all zeros for "/dev/zero" process. Choose one of the following:
Type: "dd if=\\?\Device\Harddisk1\Partition0 | hexdump -C"
Type: "hexdump.exe -C \\.\d:" where [\\.\d:] is [unformatted directory]
while printf '\0'; do printf '\0'; done | dd of=<file> bs=4M conv=sync status=progress
yes "" | tr '\n' '\0' | dd of=<file> bs=4M conv=sync status=progress
/dev/zero equivalent in windows? – Server Fault
Virtual devices are a new feature in version 0.4beta1. Because windows does
not have devices like the unix /dev/zero or /dev/random these have been
implemented inside dd. You can use these as input files to supply an infinite
amount of zeros or pseudo random data.
Download "dd for Windows" and open Windows Command-line ("cmd.exe").
Type: "cd /D [directory]" to the "dd" folder.
Type: "dd --list" to show list of Volumes, Disks, and Partitions. Locate your device.
Type: "dd if=/dev/zero of=\\?\Device\Harddisk1\Partition0 --progress"
Choose between "/dev/zero" and "/dev/random" as the write operation. Ensure you select your device based on step 3.
Wait for the zero or random write process to complete and then run hexdump to display hexadecimal value, which should read all zeros for "/dev/zero" process. Choose one of the following:
Type: "dd if=\\?\Device\Harddisk1\Partition0 | hexdump -C"
Type: "hexdump.exe -C \\.\d:" where [\\.\d:] is [unformatted directory]
/dev/zero
Function. Read operations from /dev/zero return as many null characters (0x00)
as requested in the read operation.. Unlike /dev/null, /dev/zero may be used
as a source, not only as a sink for data. All write operations to /dev/zero
succeed with no other effects. However, /dev/null is more commonly used for
this purpose. When /dev/zero is memory-mapped, e.g., with mmap, to the …
dd if=/dev/zero of=/dev/<destination partition>
dd if=/dev/zero of=foobar count=1024 bs=1024
dd if=/dev/zero of=foobar count=1 bs=1GB
Is there a /dev/null on Windows?
For people looking for Unix «special» files under Windows: here are
/dev/random and /dev/zero device drivers for Win32. – ulidtko. Dec 19, 2014 at
11:06. 10 If you need to perform in Microsoft Windows the equivalent of a
symlink to /dev/null in Linux you would open and administrator’s cmd and type:
For files: mklink c:\path\to\file.ext NUL:
type c:\autoexec.bat > NUL
echo 1 > $null
#include <stdio.h>
int main ()
{
FILE* outfile = fopen ("/dev/null", "w");
if (outfile == NULL)
{
fputs ("could not open '/dev/null'", stderr);
}
outfile = fopen ("nul", "w");
if (outfile == NULL)
{
fputs ("could not open 'nul'", stderr);
}
return 0;
}
echo 1 > nul
echo 1 > c:\nul
echo 1 > c:\users\nul
echo 1 > c:\windows\nul
freopen("NUL", "w", stderr);
mklink c:\path\to\file.ext NUL:
mklink /D c:\path\to\dir NUL:
start .\mySum 5 10 > $NUL 2>&1
robocopy .\test NUL /move /minage:30
# delete all files older than 30 days using robocopy
ERROR 123 (0x0000007B) Accessing Destination Directory \\.\NUL\
The filename, directory name, or volume label syntax is incorrect.
echo 1 > NUL
robocopy .\test NUL\null /move /minage:30
echo 1 > $null
mkdir test1
cd test1
echo "" > test1.txt
echo "" > test2.txt
echo "" > test3.txt
$path = '.\test1'
cmd.exe /c "robocopy $path NUL\null /move"
# also this works:
cmd.exe /c "robocopy $path .\NUL\null /move"
/ dev / zero echivalent în Windows?
Deoarece Windows nu are dispozitive precum unix / dev / zero sau / dev /
random acestea au fost implementate în interiorul dd. Puteți să le utilizați
ca fișiere de intrare pentru a furniza o cantitate infinită de zerouri sau
date pseudo-aleatorii. 1 . Lucrat ca un farmec, acum se reduce la zero!
Mulțumesc pentru avertisment!!!
Download 'dd for Windows' and open Windows Command-line ('cmd.exe'). Type: 'cd /D [directory]' to the 'dd' folder. Type: 'dd --list' to show list of Volumes, Disks, and Partitions. Locate your device. Type: 'dd if=/dev/zero of=\\?\Device\Harddisk1\Partition0 --progress' Choose between '/dev/zero' and '/dev/random' as the write operation. Ensure you select your device based on step 3.
Wait for the zero or random write process to complete and then run hexdump to display hexadecimal value, which should read all zeros for '/dev/zero' process. Choose one of the following: Type: 'dd if=\\?\Device\Harddisk1\Partition0 | hexdump -C' Type: 'hexdump.exe -C \\.\d:' where [\\.\d:] is [unformatted directory]
/ dev / zero ekvivalent v systému Windows?
Protože Windows nemají zařízení jako unix / dev / zero nebo / dev / random,
byla implementována uvnitř dd. Můžete je použít jako vstupní soubory k dodání
nekonečného množství nul nebo pseudonáhodných dat. 1 . Fungovalo to jako
kouzlo, nyní se …
Download 'dd for Windows' and open Windows Command-line ('cmd.exe'). Type: 'cd /D [directory]' to the 'dd' folder. Type: 'dd --list' to show list of Volumes, Disks, and Partitions. Locate your device. Type: 'dd if=/dev/zero of=\\?\Device\Harddisk1\Partition0 --progress' Choose between '/dev/zero' and '/dev/random' as the write operation. Ensure you select your device based on step 3.
Wait for the zero or random write process to complete and then run hexdump to display hexadecimal value, which should read all zeros for '/dev/zero' process. Choose one of the following: Type: 'dd if=\\?\Device\Harddisk1\Partition0 | hexdump -C' Type: 'hexdump.exe -C \\.\d:' where [\\.\d:] is [unformatted directory]