Command Reference Manual
View 237 orders by topic.
Get to know the workspace
pwdShow current locationlsList files and directoriescdSwitch working directorytreeObserve the directory structuremanQuery command manualhelpView support scoperealpathParse absolute pathswhichFind external command locationtypeIdentify built-in and external commandslocateFind a file in the indexupdatedbUpdate file indexpushdEnter the directory and push onto the directory stackpopdPop directory stackdirsShow directory stack
Organize files
mkdirCreate directorytouchCreate empty filecpCopy a file or directorymvMove or renamermDelete a file or directoryrmdirDelete empty directoriesfileDetermine file typestatView file propertiesbasenameGet the name at the end of the pathdirnameGet the parent directory pathrsyncSynchronize directories and filesgitManage code versionsmktempCreate a temporary file or directorytruncateAdjust file lengthinstallCopy and set installation permissionsrenameBatch rename based on expressionddCopy data in chunkssyncFlush file system cachesha256sumGenerate or inspect SHA-256 digestmd5sumGenerate or inspect MD5 digestcksumCalculate CRC check valuebase64Encode or decode Base64
Real terminal exercises
Operate from Linux or WSL terminal. Create a temporary exercise directory first; some parameters of macOS are different.
Task
Back up note.txt to backup.txt, and then rename the original file to meeting.txt.
Prepare
LAB_DIR=$(mktemp -d)
cd "$LAB_DIR"
printf 'meeting notes\n' > note.txtexamine
meeting.txt has the same content as backup.txt, note.txt no longer exists.
Real files may encounter permission or overwrite prompts. Only operate in this temporary directory.
Reference operation
cp note.txt backup.txt
mv note.txt meeting.txt
ls
cmp meeting.txt backup.txtLet commands collaborate
echoOutput a piece of textprintfOutput text according to formatteeOutput and save pipeline contentsxargsConvert input into command parametersexportSet environment variablesenvView environment variablesprintenvOutput the value of environment variableunsetRemove variableshistoryView command historyclearClear the terminal displaytrueReturn success statusfalseReturn failure statusseqGenerate a sequence of numberssleepPause for specified timealiasSet command aliasunaliasRemove command aliassourceRead script in current ShellreadRead variables from inputbashRun the Bash scriptshRun the POSIX Shell scriptcommandControl command lookupjobsView current Shell jobsbgResume background jobfgResume foreground jobwaitWait for child process to endnohupIgnore hangup signal and runtimeoutLimit command running timewatchDisplay command results periodicallytimeMeasure run timeulimitView or set resource limitssetSet Shell behaviortrapHandle exit or signaltmuxManage terminal sessionsscreenKeep terminal session
Real terminal exercises
Operate from Linux or WSL terminal. Create a temporary exercise directory first; some parameters of macOS are different.
Task
Write the error line to errors.txt and display it in the terminal, then check the exit code.
Prepare
LAB_DIR=$(mktemp -d)
cd "$LAB_DIR"
printf 'INFO ready\nERROR timeout\n' > app.logexamine
Both screen and errors.txt have ERROR timeout; the exit code for the immediate pipe check is 0.
Real Shell has multiple processes and their own exit codes; the default pipe exit code is the last one.
Reference operation
grep ERROR app.log | tee errors.txt
echo $?
cat errors.txtRead and process text
catRead and concatenate textlessRead text in pagesmoreView text in pagesheadRead the first few linestailRead last few linesgrepFilter text by patternfindFind paths by name or typewcCount lines, words and bytessortSort lines of textuniqMerge adjacent duplicate rowscutExtract columns or characterstrReplace or delete characterssedReplace text or select linesawkExtract structured text fieldsdiffCompare two text filesvimEdit files in terminalnanoModify files with a simple editornlNumber lines of texttacOutput lines of text in reverse orderrevReverse characters line by linepasteSplicing text columns horizontallycommCompare sorted listscmpCompare files to see if they are the sameexpandConvert Tab to spacesunexpandConvert leading spaces to TabfoldWrap long textrgFast recursive text searchjqHandle JSONyqHandle YAMLjoinMerge sorted tables by common fieldsfmtReformat paragraphs word by wordcolumnArrange text tablestringsExtract printable text from binaryodView file byte representationhexdumpShow hexadecimal bytesxxdView or restore hex dumpiconvConvert text encodingdos2unixConvert Windows to newlinesplitSplit file by linescsplitSplit text by patternbcEvaluate a numeric expression
Real terminal exercises
Operate from Linux or WSL terminal. Create a temporary exercise directory first; some parameters of macOS are different.
Task
Find the ERROR line, display the line number, and count the number of errors.
Prepare
LAB_DIR=$(mktemp -d)
cd "$LAB_DIR"
printf 'INFO ready\nERROR timeout\nINFO done\nERROR disk\n' > app.logexamine
The error is located on lines 2 and 4 of 2. Then use less app.log to read, and press q to exit.
less will enter the paging interface; q will exit, / search. The sandbox only outputs snapshots.
Reference operation
grep -n ERROR app.log
grep -c ERROR app.log
less app.logPermissions and links
chmodModify permissionschownModify ownerumaskSet new file permission masklnCreate symbolic linkreadlinkView symbolic link targetssudoExecute command as administratorgroupsQuery user groupchgrpModify the group to which the file belongsgetfaclView extended access controlsetfaclSet up extended access controllsattrQuery file attribute flagschattrModify file attribute flagssuSwitch user sessionpasswdChange account passworduseraddcreate AccountusermodModify account propertiesuserdelDelete accountgroupaddCreate user groupgetentQuery system account database
Real terminal exercises
Operate from Linux or WSL terminal. Create a temporary exercise directory first; some parameters of macOS are different.
Task
Make run.sh readable, writable, and executable by only you, and then actually run it.
Prepare
LAB_DIR=$(mktemp -d)
cd "$LAB_DIR"
printf '#!/bin/sh\nprintf "ready\\n"\n' > run.shexamine
ls -l displays -rwx------; executes the script and outputs ready.
The real system execution bit restricts script startup; the sandbox does not run arbitrary scripts, nor does it simulate full access control.
Reference operation
chmod 700 run.sh
ls -l run.sh
./run.shPackaging and compression
tarPack, view and restore archivesgzipcompressed filegunzipRecover compressed fileszipCreate ZIP archiveunzipUnzip the ZIP archivebzip2Use bzip2 compressionbunzip2Unzip the bzip2 filexzUse xz compressionunxzUnzip the xz filezcatRead gzip filezgrepSearch for gzip textzstdUse Zstandard compression7zManage multiple archive formats
Real terminal exercises
Operate from Linux or WSL terminal. Create a temporary exercise directory first; some parameters of macOS are different.
Task
Archive the source directory, list the contents, restore to restored, and compare the original and copy.
Prepare
LAB_DIR=$(mktemp -d)
cd "$LAB_DIR"
mkdir source restored
printf 'hello\n' > source/note.txtexamine
The archive contains source/note.txt; the recovered text is identical to the original.
The real tar/gzip file is generated here; the sandbox only saves the teaching snapshot.
Reference operation
tar -czf source.tar.gz source
tar -tf source.tar.gz
tar -xf source.tar.gz -C restored
cmp source/note.txt restored/source/note.txtobservation system
psView process listpgrepCheck process number by namekillSend signal to processpkillEnd process by nametopView system process snapshotfreeView memory overviewdfView file system spaceduEstimated directory usageunameView kernel informationwhoamiShow current useridView users and user groupshostnameView host namedateView dateuptimeView running timenprocQuery the number of available processorswhoView login sessionwView sessions and loadttyView terminal device namelscpuView CPU topologylsblkView block devices and file systemsfindmntView mounting relationshipsvmstatObserve memory and CPU indicatorsdmesgView kernel messageshtopInteractively view process resourceslsofView open files and portsfuserFind processes occupying files or portsiostatWatch the disk with the CPU indicatorpidstatObserve process resource usagesarQuery system performance recordsniceSpecify process scheduling priorityreniceAdjust the priority of existing processesioniceAdjust I/O scheduling prioritystraceTracing system callsperfSampling performance eventsmountMount file systemumountUnmount file systemblkidQuery block device identifierfdiskView or edit partitionspartedManage disk partitionsmkfsCreate file systemfsckCheck file systemswaponEnable or query swap spaceswapoffDisable swap spacelsmodList kernel modulesmodinfoQuery kernel module informationmodprobeLoad kernel modulelsusbView USB devicelspciView PCI devicegetconfView system configuration values
Real terminal exercises
Operate from Linux or WSL terminal. Create a temporary exercise directory first; some parameters of macOS are different.
Task
Check the space of the file system where the current directory is located and the occupation of this temporary directory, and then check the memory.
Prepare
LAB_DIR=$(mktemp -d)
cd "$LAB_DIR"
printf 'sample\n' > sample.txtexamine
Can point out the Available of df and the available fields of free, and explain why the du and file byte counts may be different.
Actual results will vary from machine to machine; du counts allocated blocks, free and available are estimates of available memory.
Reference operation
df -h .
du -sh .
free -hTroubleshoot the network
ipQuery address and routingssView sockets and listening portspingCheck host connectivitydigQuery DNS recordsnslookupQuery host addresscurlRequest URL or download contentwgetDownload filesshLog in to the remote machinescpCopy files via SSHhostQuery DNStracerouteProbing network routestracepathDetection path and MTUmtrContinuously observe routing and packet lossncTest connection or listening portsocatConnect data streams to socketstcpdumpCapture network packetsnmapDetect authorized host portethtoolQuery network interface informationnmcliManage NetworkManager connectionssftpTransfer files interactively through SSHssh-keygenGenerate SSH keyssh-copy-idInstall the SSH public keyopensslCheck TLS with certificate
Real terminal exercises
Operate from Linux or WSL terminal. Create a temporary exercise directory first; some parameters of macOS are different.
Task
View the local machine address, default route and listening port, and observe the HTTPS response header.
Prepare
LAB_DIR=$(mktemp -d)
cd "$LAB_DIR"
# 此题只读取网络状态,不修改配置。examine
Can find the network interface, default route (if any), and HTTPS response status.
Real network requests may timeout; proxies, DNS, and offline status all affect the results. ip, ss may need to be installed first.
Reference operation
ip addr
ip route
ss -tuln
curl -I --max-time 10 https://example.comManagement services
systemctlQuery and Management systemd ServicesjournalctlView service logsaptManage Debian/Ubuntu packagescrontabSchedule periodic tasksdockerManage containersserviceManage traditional serviceshostnamectlQuery or set hostnametimedatectlQuery time and time zoneloginctlQuery login sessionatSchedule one-time tasksdpkgQuery Debian packageapt-cacheQuery APT package metadataapt-getManage APT package in scriptdnfManage Fedora packagesyumManagement RPM series software packagesrpmQuery RPM packagepacmanManage Arch packagesapkManage Alpine packagespodmanManage containers and imageskubectlManage Kubernetes resourcesnginxCheck Web service configurationlogrotateRotate log files
Real terminal exercises
Operate from Linux or WSL terminal. Create a temporary exercise directory first; some parameters of macOS are different.
Task
Read the user service list and recent user logs without changing the service status.
Prepare
LAB_DIR=$(mktemp -d)
cd "$LAB_DIR"
# 需要使用 systemd 的 Linux;WSL 或容器可能没有服务管理器。examine
Can distinguish active and enabled and find a log; if the environment does not support systemd, keep this question first.
Real services rely on permissions and service managers. active represents the current running, enabled represents the startup strategy.
Reference operation
systemctl --user list-units --type=service
systemctl --user list-unit-files --type=service
journalctl --user -n 5 --no-pagermission challenge
Real terminal exercises
Operate from Linux or WSL terminal. Create a temporary exercise directory first; some parameters of macOS are different.
Task
Filter developer from the list, extract the names, sort them and remove duplicates, and save them as developers.txt.
Prepare
LAB_DIR=$(mktemp -d)
cd "$LAB_DIR"
printf 'bob,developer\nalice,designer\ncarol,developer\nbob,developer\n' > users.csvexamine
developers.txt only has bob and carol, two rows in alphabetical order.
This question combines multiple tools in a real Shell to check whether you can transfer single command knowledge to a complete process.
Reference operation
grep ',developer$' users.csv | cut -d , -f 1 | sort | uniq > developers.txt
cat developers.txt