Post

Windows & POSIX CLI Reference

Comprehensive command-line reference comparing Windows and Linux for system administration and daily tasks.

Windows & POSIX CLI Reference

A comprehensive command-line reference comparing equivalent utilities between Windows and POSIX-compliant systems (Linux, macOS, FreeBSD). Organised into logical sections covering the most commonly used system administration and file management tasks for desktop and server environments.

File Operations

TaskPOSIX SystemsWindowsNotes
Display file contentscat filenametype filenameBoth systems support more
Copy filecp source destcopy source destBoth support recursive copying with options
Move/rename filemv oldname newnamemove oldname newnameWindows also has ren, POSIX has rename
Delete filerm filenamedel filenameWindows also supports erase
Delete file forcefullyrm -f filenamedel /f filenameForce deletion of read-only files
Delete recursivelyrm -rf directoryrmdir /s directoryWindows also supports rd /s
Create empty filetouch filenameecho. > filenameWindows: type nul > filename also works
Find filesfind /path -name "*.txt"dir /s *.txtWindows: forfiles for advanced searches
Compare filesdiff file1 file2fc file1 file2Windows: comp for binary comparison
File permissionschmod 755 filenameicacls filename /grant user:FDifferent permission models entirely
File ownershipchown user:group filenametakeown /f filenameWindows: icacls for detailed permissions

Directory Operations

TaskPOSIX SystemsWindowsNotes
List directory contentslsdirPOSIX: ls -la for detailed view
List with detailsls -ldir /qShow ownership and permissions
List hidden filesls -adir /aInclude hidden and system files
Create directorymkdir dirnamemkdir dirnameBoth support -p for parent directories
Remove empty directoryrmdir dirnamermdir dirnameDirectory must be empty
Current directorypwdcdWindows: echo %cd% also works
Change directorycd /path/to/dircd \path\to\dirUse forward/back slashes respectively
Directory sizedu -sh dirnamedir /s dirnameWindows: shows total size at end
Directory treetreetreeBoth systems have tree command

Text Processing

TaskPOSIX SystemsWindowsNotes
Search text in filesgrep "pattern" filenamefindstr "pattern" filenameWindows: /i for case-insensitive
Search recursivelygrep -r "pattern" /pathfindstr /s "pattern" *Search in subdirectories
Count lineswc -l filenamefind /c /v "" filenameWindows counts non-empty lines
Head of filehead -n 10 filenamemore +10 filenameWindows: limited built-in options
Tail of filetail -n 10 filenamepowershell Get-Content filename -Tail 10Windows: PowerShell required for tail
Sort file contentssort filenamesort filenameBoth systems support sorting
Remove duplicatessort filename \| uniqsort filename \| uniqWindows has limited uniq functionality
Replace textsed 's/old/new/g' filenamepowershell (Get-Content file) -replace 'old','new'Windows: PowerShell for advanced replacement

Network Operations

TaskPOSIX SystemsWindowsNotes
Test connectivityping hostnameping hostnameBoth support same basic options
Trace routetraceroute hostnametracert hostnameDifferent command names
Network configurationip addr showipconfigPOSIX: ifconfig on older systems
DNS lookupnslookup hostnamenslookup hostnameBoth systems identical
Network connectionsnetstat -annetstat -anBoth systems identical
Active connectionsss -tulnnetstat -an \| findstr LISTENPOSIX ss is modern replacement
Download filewget urlpowershell Invoke-WebRequest urlWindows: curl available in newer versions
Show routing tableroute -nroute printDifferent syntax
ARP tablearp -aarp -aBoth systems identical
Flush DNS cachesudo systemctl restart systemd-resolvedipconfig /flushdnsPOSIX varies by distribution

System Information

TaskPOSIX SystemsWindowsNotes
System informationuname -asysteminfoWindows provides more detailed output
OS versioncat /etc/os-releaseverPOSIX location varies by distribution
HostnamehostnamehostnameBoth systems identical
Uptimeuptimesysteminfo \| findstr "System Boot Time"Windows: more verbose
Memory usagefree -hwmic OS get TotalVisibleMemorySize,FreePhysicalMemory /valueWindows: WMI query
Disk usagedf -hwmic logicaldisk get size,freespace,captionWindows: WMI query
CPU informationlscpuwmic cpu get name,numberofcores,numberoflogicalprocessors /valueWindows: WMI query
Hardware infolshwwmic computersystem get model,manufacturer /valuePOSIX: may need installation
Environment variablesenvsetList all environment variables
Specific env variableecho $PATHecho %PATH%Different syntax for variables

Process Management

TaskPOSIX SystemsWindowsNotes
List processesps auxtasklistPOSIX: many options available
Kill process by PIDkill 1234taskkill /pid 1234Windows: /f to force
Kill process by namekillall processnametaskkill /im processname.exeWindows: include .exe extension
Process treepstreetasklist /vWindows: limited tree view
Top processestoptasklist /fi "memusage gt 100000"Windows: filter by memory usage
Background processcommand &start /b commandRun process in background
Process prioritynice -n 10 commandstart /low commandSet process priority
Process monitoringhtoptasklist /fi "status eq running"POSIX htop may need installation

User Management

TaskPOSIX SystemsWindowsNotes
Current userwhoamiwhoamiBoth systems identical
List userscat /etc/passwdnet userDifferent approaches
Add usersudo useradd usernamenet user username password /addAdmin privileges required
Delete usersudo userdel usernamenet user username /deleteAdmin privileges required
Change passwordpasswdnet user username *Interactive password change
User groupsgroups usernamenet user usernameWindows shows group membership
Switch usersu - usernamerunas /user:username cmdDifferent syntax
Sudo equivalentsudo commandrunas /user:administrator cmdWindows: Run as administrator

File Permissions & Security

TaskPOSIX SystemsWindowsNotes
View permissionsls -l filenameicacls filenameWindows shows ACLs
Change permissionschmod 755 filenameicacls filename /grant user:RXDifferent permission models
Change ownershipchown user:group filenametakeown /f filenameWindows: separate ownership command
Set file attributeschattr +i filenameattrib +r filenameDifferent attribute systems
View file attributeslsattr filenameattrib filenameDifferent commands

Archive Operations

TaskPOSIX SystemsWindowsNotes
Create tar archivetar -czf archive.tar.gz filespowershell Compress-Archive files archive.zipDifferent formats
Extract tar archivetar -xzf archive.tar.gzpowershell Expand-Archive archive.zipPowerShell for zip
List archive contentstar -tzf archive.tar.gzpowershell Get-ChildItem archive.zipPowerShell required
Create zip archivezip -r archive.zip filespowershell Compress-Archive files archive.zipzip may need installation on POSIX

Environment & Variables

TaskPOSIX SystemsWindowsNotes
Set variableexport VAR=valueset VAR=valuePOSIX: session-wide, Windows: temporary
Unset variableunset VARset VAR=Windows: set to empty string
Persistent variableecho 'export VAR=value' >> ~/.bashrcsetx VAR valueDifferent persistence methods
Show PATHecho $PATHecho %PATH%Different variable syntax
Add to PATHexport PATH=$PATH:/new/pathset PATH=%PATH%;C:\new\pathDifferent path separators (: vs ;)

Common Environment Variables

PurposePOSIX SystemsWindows (CMD)Windows (PowerShell)Notes
Current user$USER or $LOGNAME%USERNAME%$env:USERNAMEUsername of logged-in user
User home directory$HOME%USERPROFILE%$env:USERPROFILEUser’s home folder path
Current directory$PWD%CD%$PWDPresent working directory
System PATH$PATH%PATH%$env:PATHExecutable search paths
Hostname$HOSTNAME%COMPUTERNAME%$env:COMPUTERNAMEComputer/machine name
Operating system$OSTYPE%OS%$env:OSOperating system identifier
Temp directory$TMPDIR or /tmp%TEMP% or %TMP%$env:TEMPTemporary files location
Shell/Command proc$SHELL%COMSPEC%$PSVersionTableDefault shell/command processor
System root/%SYSTEMROOT%$env:SYSTEMROOTSystem installation directory
Program files/usr or /opt%PROGRAMFILES%$env:PROGRAMFILESDefault program installation directory
System architecture$HOSTTYPE or uname -m%PROCESSOR_ARCH%$env:PROCESSOR_ARCHCPU architecture (x86, x64, ARM)
Number of CPUs$NPROC or nproc%NUMBER_OF_PROC%$env:NUMBER_OF_PROCAvailable processor cores
User profile path$HOME%USERPROFILE%$HOMEUser’s profile directory
Application data$HOME/.config%APPDATA%$env:APPDATAUser application data directory
Local app data$HOME/.local/share%LOCALAPPDATA%$env:LOCALAPPDATALocal application data directory
Desktop path$HOME/Desktop%USERPROFILE%\Desktop$HOME\DesktopUser’s desktop folder
Documents path$HOME/Documents%USERPROFILE%\Docs$HOME\DocumentsUser’s documents folder
System driveN/A (use /)%SYSTEMDRIVE%$env:SYSTEMDRIVEDrive containing Windows (usually C:)
Random number$RANDOM%RANDOM%Get-RandomGenerate random number
Date/Time$DATE or date%DATE% / %TIME%Get-DateCurrent date and time
Error level$?%ERRORLEVEL%$LASTEXITCODEExit code of last command
Process ID$$N/A$PIDCurrent process identifier
Terminal type$TERMN/A$Host.NameTerminal/console type
Display (GUI)$DISPLAYN/AN/AX11 display for GUI applications
Language/Locale$LANG or $LC_ALLN/A$PSCultureSystem language and locale settings

Accessing Environment Variables

TaskPOSIX SystemsWindows (CMD)Windows (PowerShell)Notes
Display single varecho $VARecho %VAR%echo $env:VARShow specific variable
Display all varsenv or printenvsetGet-ChildItem env:List all environment vars
Check if var exists[ -n "$VAR" ]if defined VARTest-Path env:VARTest variable existence
Set temporary varVAR=valueset VAR=value$env:VAR = "value"Session-only variable
Set permanent varexport VAR=valuesetx VAR value[Environment]::SetVariablePersistent across sessions
Unset variableunset VARset VAR=Remove-Item env:VARRemove environment variable

Logic and Conditional Operators

Command Chaining and Logic

OperationBash/POSIX ShellWindows CMDPowerShellNotes
AND (success chain)command1 && command2command1 && command2command1; command2Run second if first succeeds
OR (failure chain)command1 \|\| command2command1 \|\| command2command1; if (!$?) { command2 }Run second if first fails
Sequentialcommand1; command2command1 & command2command1; command2Run both regardless of result
Pipe outputcommand1 \| command2command1 \| command2command1 \| command2Pass output to next command

Comparison Operators

ComparisonBashWindows CMDPowerShellNotes
Equal[ "$a" -eq "$b" ]if %a%==%b%$a -eq $bString/numeric equality
Not equal[ "$a" -ne "$b" ]if not %a%==%b%$a -ne $bString/numeric inequality
Greater than[ "$a" -gt "$b" ]if %a% gtr %b%$a -gt $bNumeric comparison
Less than[ "$a" -lt "$b" ]if %a% lss %b%$a -lt $bNumeric comparison
Greater or equal[ "$a" -ge "$b" ]if %a% geq %b%$a -ge $bNumeric comparison
Less or equal[ "$a" -le "$b" ]if %a% leq %b%$a -le $bNumeric comparison
String equal[ "$a" = "$b" ]if "%a%"=="%b%"$a -eq $bExact string match
String not equal[ "$a" != "$b" ]if not "%a%"=="%b%"$a -ne $bString inequality

File and Directory Tests

TestBashWindows CMDPowerShellNotes
File exists[ -f "$file" ]if exist "%file%"Test-Path $fileCheck if file exists
Directory exists[ -d "$dir" ]if exist "%dir%\"Test-Path $dir -PathType ContainerCheck if directory exists
File readable[ -r "$file" ]N/A(Get-Acl $file).AccessCheck read permissions
File writable[ -w "$file" ]N/A(Get-Acl $file).AccessCheck write permissions
File executable[ -x "$file" ]N/A(Get-Command $file -ErrorAction SilentlyContinue)Check execute permissions
File empty[ ! -s "$file" ]if %~z1==0(Get-Item $file).Length -eq 0Check if file is empty

Exit Codes and Error Handling

OperationBashWindows CMDPowerShellNotes
Last exit codeecho $?echo %errorlevel%echo $LASTEXITCODEShow previous command result
Exit with codeexit 1exit /b 1exit 1Exit script with specific code
Success (exit 0)exit 0exit /b 0exit 0Successful completion
Suppress errorscommand 2>/dev/nullcommand 2>nulcommand -ErrorAction SilentlyContinueHide error output

Tips for Cross-Platform Usage

  1. Path Separators: POSIX uses / while Windows uses \ (though Windows accepts / in many contexts)
  2. Case Sensitivity: POSIX is case-sensitive, Windows is not
  3. Line Endings: POSIX uses LF (\n), Windows uses CRLF (\r\n)
  4. Wildcards: Both support * and ?, but behavior may vary
  5. Permissions: POSIX uses octal permissions (755), Windows uses Access Control Lists (ACLs)
  6. Environment Variables: POSIX uses $VAR, Windows uses %VAR%
  7. Command Chaining: Both support && (AND) and || (OR), POSIX also supports ;
  8. Redirection: Both support > (redirect), >> (append), and | (pipe)

POSIX Only

Package Management Comparison

TaskDebian/Ubuntu (APT)Red Hat/Fedora (DNF/YUM)FreeBSD (pkg)Notes
Update package listsudo apt updatesudo dnf check-updatesudo pkg updateRefresh repository metadata
Upgrade packagessudo apt upgradesudo dnf upgradesudo pkg upgradeInstall available updates
Install packagesudo apt install packagesudo dnf install packagesudo pkg install packageInstall new software
Remove packagesudo apt remove packagesudo dnf remove packagesudo pkg delete packageRemove software
Search packagesapt search keyworddnf search keywordpkg search keywordFind available packages
Show package infoapt show packagednf info packagepkg info packageDisplay package details
List installedapt list --installeddnf list installedpkg infoShow installed packages
Clean cachesudo apt cleansudo dnf clean allsudo pkg cleanClear package cache
Autoremove unusedsudo apt autoremovesudo dnf autoremovesudo pkg autoremoveRemove orphaned packages

Windows Only

PowerShell

TaskCommandNotes
List processesGet-ProcessPowerShell alternative to tasklist
Stop processStop-Process -Name processnamePowerShell process management
Get system infoGet-ComputerInfoComprehensive system information
Network adaptersGet-NetAdapterModern network configuration
Event logsGet-EventLog -LogName SystemView system events
ServicesGet-ServiceList Windows services
Install softwarewinget install packagePackage manager (Windows 10+)

Windows Subsystem for Linux (WSL)

TaskCommandNotes
List distributionswsl --listShow installed Linux distributions
Set default distrowsl --set-default UbuntuChange default Linux environment
Run specific distrowsl -d UbuntuLaunch specific distribution
Shutdown WSLwsl --shutdownStop all WSL instances

Terminology Acronyms

AcronymFull FormDescription
ACLAccess Control ListWindows file permission system
APTAdvanced Package ToolDebian/Ubuntu package management system
ARPAddress Resolution ProtocolNetwork protocol for IP to MAC address mapping
BSDBerkeley Software DistributionUnix-like operating system family
DNFDandified YUMModern package manager for Red Hat-based distributions
DNSDomain Name SystemInternet naming system
PIDProcess IdentifierUnique number assigned to running processes
POSIXPortable Operating System InterfaceIEEE standard for Unix-like operating system compatibility
SSHSecure ShellEncrypted network protocol for remote access
TTYTeletypewriterTerminal interface
WMIWindows Management InstrumentationWindows system management interface
WSLWindows Subsystem for LinuxLinux compatibility layer for Windows
YUMYellowdog Updater ModifiedLegacy package manager for Red Hat-based distributions

Command Acronyms

CommandFull FormDescription
catConcatenateDisplay and concatenate file contents
cdChange DirectoryNavigate between directories
cpCopyCopy files and directories
dfDisk FreeDisplay filesystem disk space usage
duDisk UsageDisplay directory space usage
grepGlobal Regular Expression PrintSearch text using patterns
lsListList directory contents
mvMoveMove/rename files and directories
psProcess StatusDisplay running processes
pwdPrint Working DirectoryDisplay current directory path
rmRemoveDelete files and directories
sedStream EditorStream-oriented text editor for filtering/transform
suSwitch User (or Substitute User)Change user identity
tarTape ArchiveArchive files (originally for tape storage)
wcWord CountCount lines, words, and characters
This post is licensed under CC BY 4.0 by the author.