Linux Study Notes
Linux Study Notes Basic Linux Commands
Basic Linux Commands
Linux has no drive letters; all files are stored under the root directory.
cdchange directorycd /home/userchange to the specified directorycd /change to the root directorycd ../change to the parent directorycd ./change to the current directorycd ~change to the user directory (for the root user, this is equivalent tocd /root)cd -change to the previously jumped-to directory
pwdshow the current directorylslist files in the directory (only file names, no details)ls -llist files in the directory in list form (with details, equivalent toll)ls -alist all files (including hidden files)ls -allist all files in the directory in list form (with details, equivalent to-a -l)ls /rootlist files in the specified directory (here, under root)
mkdircreate a directory (make directory)mkdir dirnamecreate a directorydirnamein the current folder;mkdir /dirnamecreatesdirnameunder the root directorymkdir dirname1 dirname2create directoriesdirname1anddirname2in the current foldermkdir -p dirname1/dirname2create directorydirname1/dirname2in the current folder;-pmeans the parent directorydirname1can be created
touchcreate a file (the content appended afterward is the same as the mkdir command)echooutput, same asprintin other languagesecho "hello world"outputhello worldecho "hello world" > file.txtcreate the file and writehello world(overwrite mode)echo "hello world" >> file.txtcreate the file and writehello world(append mode)echo $PATHoutput the value of the variablePATH
cat,more,less,head,tailcommands can all view file contentscat file.txtoutput the contents offile.txt(all contents)more file.txtoutput the contents offile.txt(displayed line by line, press Enter for the next line, q to quit, has a progress bar)less file.txtoutput the contents offile.txt(displayed line by line, press Enter for the next line, q to quit, no progress bar)head file.txtoutput the first 10 lines offile.txt(head -20 file.txtoutputs the first 20 lines offile.txt)tail file.txtoutput the last 10 lines offile.txt(tail -20 file.txtoutputs the last 20 lines offile.txt)tail -f file.txtcontinuously output the last 10 lines offile.txt(new content is appended to the output, commonly used to view log files)
cpcopy files or directories (copy)cp file.txt /home/usercopyfile.txtto the specified directorycp -r dirname /home/usercopy directorydirnameto the specified directory (-rmeans recursive copy, i.e., copy all files and subdirectories under the directory)
mvmove files or directories (move) cutmv file.txt /home/usermovefile.txtto the specified directorymv dirname /home/usermove directorydirnameto the specified directorymv dirname1 dirname2rename directorydirname1todirname2(ifdirname2already exists, move the contents ofdirname1intodirname2; if it doesn’t exist, it’s equivalent to renaming)
rmdelete files or directories (remove)rm file.txtdeletefile.txtrm -r dirnamedelete directorydirnameand its contents (-rmeans recursive delete)rm -rf dirnamedelete directorydirnameand its contents (-rfmeans recursive delete without confirmation prompt, force delete)
vi file.txteditfile.txt- after entering the file, first press
ito enter insert mode - after editing, press
Escto exit insert mode - in a non-other mode, enter
:wqto save and quit (:wsave,:qquit,:wq!force save and quit) vimis also an editor that highlights code; it requires installing additional packages
- after entering the file, first press
gzip,tarcompress filesgzip file.txtcompressfile.txt(automatically generatesfile.txt.gzand deletes the source file)gzip -d file.txt.gzdecompressfile.txt.gz(automatically deletes the source file)gzip -k file.txtcompressfile.txt(does not delete the source file)tar -zcvf file.tar.gz dirnamecompress directorydirname(automatically generatesfile.tar.gzand deletes the source directory)tar -xvf file.tar -C /home/filedecompressfile.tarto the specified directory/home/filezipis also a compression format, but requires installing additional packages
yum install -y packageinstall software on CentOS (apt install -y packageon Ubuntu)grepsearchgrep -n string file.txtsearch for stringstringinfile.txtand show line numbers (-n)grep -i string file.txtsearch for stringstringinfile.txtand ignore case (-i)grep -v string file.txtsearch for stringstringinfile.txtand invert the result (-v)ls | grep stringsearch for stringstringin the result of thelscommand (lscan be replaced with other commands such asps -ef, etc.)
dateshow the current timedate -s "2026-01-03 12:00:00"set the timentpdate time1.aliyun.comsynchronize the time
scpremote copy of files (copy files between two machines)scp file.txt user@remote_host:/home/usercopy filefile.txtto the remote hostremote_host(logging in as useruser) under/home/user
chmodmodify file permissionschmod 755 file.txtmodify the permissions offile.txtto 755 (owner can read/write/execute, others can read/execute)chmod +x script.shadd execute permission to the scriptchmod -R 755 dirnamerecursively modify permissions of all files in the directory
chownmodify file ownerchown user file.txtchange the owner offile.txtto useruserchown user:group file.txtchange the owner offile.txttouserand the group togroupchown -R hadoop:hadoop /usr/local/hadooprecursively modify the directory owner and group
sudoexecute a command with administrator privilegessudo apt install packageinstall a software package with administrator privilegessudo -iswitch to the root user (simulate a full login)sudo -sswitch to the root user’s shell
suswitch usersu - usernameswitch tousernameuser and load its environment variablessu usernameswitch tousernameuser but do not load environment variables
psview process statusps -efshow detailed information of all processesps auxshow detailed information of all processes (more commonly used)ps -ef | grep javafind all Java processes
killterminate a processkill PIDsend the default signal to terminate the process (process ID required)kill -9 PIDforce terminate the processkillall process_nameterminate processes by process name
top/htopmonitor system resources in real timetopshow process and resource usage in real time (press q to quit, P to sort by CPU, M to sort by memory)htopa more intuitive monitoring tool (requires installation)
dfview disk space usagedf -hshow disk usage in human-readable format (GB, MB, etc.)df -Tshow the file system type
duview directory sizedu -sh dirnameview the total size of directorydirnamedu -ah dirnameshow the size of all files and directories under the directorydu --max-depth=1 dirnameshow the size of the first-level subdirectories under the directory
findfind filesfind /home -name "file.txt"find a file namedfile.txtunder/homefind . -type f -name "*.log"find all.logfiles under the current directoryfind /var/log -mtime -7find files modified within the last 7 days under/var/log
lncreate a symbolic linkln -s /path/to/source /path/to/linkcreate a symbolic link to the source file (similar to a Windows shortcut)ln source linkcreate a hard link
netstat/ssview network connection statusnetstat -tulnview all listening TCP and UDP portsnetstat -an | grep 8080view the connection status of port 8080ss -tulna more modern command for viewing network status
manview help documentationman lsview detailed help for thelscommandman 5 passwdview the configuration file format description (5 indicates the section)
jpsview Java processes (bundled with the JDK)jpsshow all Java processes and their process IDsjps -lshow the full class name or JAR file namejps -vshow JVM startup parameters
Use “ (the key above Tab) to execute a command, e.g., echo `ls /home/` will list all files under the /home/ directory (equivalent to first executing ls /home/ and then outputting).
Recommended Linux Settings
Versions differ and commands vary; look them up yourself. Here are some common settings:
Static IP, server naming, setting username-IP mapping, firewall configuration, passwordless SSH login connection, etc.
Shell Scripts
touch file.sh create a script file
vi file.sh edit a script file
sh file.sh execute a script file (or use chmod +x file.sh to grant execute permission, then ./file.sh)
- r readable, w writable, x executable
In a file you can use the references: $0: script name, $1: first parameter, $2: second parameter, …, $#: number of parameters, $*: display all parameters as a string, $@: display all parameters as an array.
After that, you can directly use sh file.sh var1 var2 to execute the script file, where var1 and var2 are parameters passed to the script.
Note: When writing scripts, be sure to use
#!/bin/bashas the beginning of the script file, and save it with UNIX+UTF-8 encoding.
Be careful not to add spaces arbitrarily around the equals sign: assignment cannot have spaces (treated as a whole), while comparison must have spaces (treated as separate parts).
Basics
Variables
Variable declaration: variable_name="value". Note that there can be no spaces between the variable name, the equals sign, and the value; other rules are the same as other syntaxes.
After assignment, add ${} before the variable name, e.g., ${variable_name} to get the variable value (the {} can be omitted).
Use the unset command to delete a variable, e.g., unset variable_name; after deletion, echoing again will output nothing.
Strings
Double quotes are recommended. Double quotes can contain variables (v="string${var1}", var1 will be automatically replaced with var1’s value) and can contain escape characters.
- Single quote
': content is output as-is, variable substitution is not supported - Double quote
": supports variable substitution and escape characters - Backtick
`: command execution (using$()is more recommended)
String concatenation: string1="hello" string2="world" echo ${string1} ${string2}
Add # before a variable to get the string length: echo ${#string}
Substring extraction: echo ${string:1:4}, extract 4 characters starting from index 1; echo ${string:4}, remove the first 4 characters of the string.
Console Input
The read command can get user input: read var1 var2, where var1 and var2 are variable names, and the entered content is automatically assigned to variables var1 and var2.
read -p "Please enter:" var1 after entering content and pressing Enter, it will automatically print the prompt and assign it to variable var1.
Expressions
In shell scripts, the expr command can be used for addition, subtraction, multiplication, and division calculations, e.g., expr 1 + 2. Note that there must be spaces between operators (you cannot write expr 1+2). Multiplication requires the escape character \*, e.g., expr 2 \* 3.
You can also use $(()) to represent an expression, e.g., echo $(( 1 + 2 )); or use $[], e.g., echo $[ 1 + 2 ]. In $(()) and $[], you can directly use mathematical operators +, -, *, /, %, and comparison operators >, <, >=, <=, ==, != without escaping.
- In
$(()), variables can be used without the$sign, e.g.,echo $((a + b)) $(())supports increment/decrement:((i++)),((i--))letcommand:let a=1+2orlet i++
In the test command or [ ] conditional test, string comparison uses ==, !=, while numeric comparison requires: -eq equal, -ne not equal, -gt greater than, -lt less than, -ge greater than or equal, -le less than or equal.
&& logical AND, || logical OR.
Arrays
Array declaration: array=(element1 element2 element3 ...). Note that there can be no spaces between the array name and the equals sign, and array elements are separated by spaces or commas. Also, shell only has one-dimensional arrays, i.e., arrays cannot be nested.
Get array elements: echo ${array[index]}, get all array elements: echo ${array[*]}, get array length: echo ${#array[*]} (the * can be replaced with @, consistent with the parameter passing described above).
Conditional Statements
Use if elif else fi to create conditional statements.
if [ $a -gt $b ]; then echo "a is greater than b"elif [ $a -eq $b ]; then echo "a equals b"else echo "a is less than b"fiLoop Statements
Use for in do done to create loop statements.
for i in 1 2 3 4 5; do echo $idone
for i in {1..10}; do echo $idone
arr=(a,b,c)len = ${#arr[@]}for ((i=0; i < $len; i++)); do echo ${arr[$i]}done
for i in $arr; do echo $idoneWrite a script that grants permission to all files under a folder:
a=`ls $1`for file in $a; do chmod u+x $file echo "Permission granted: $file"doneUse while do done to create loop statements.
i=1while [ $i -le 5 ]; do echo $i ((i++))doneUse until do done to create loop statements (loop until the condition is met).
i=1until [ $i -gt 5 ]; do echo $i ((i++))doneLike other languages, using break in a loop can break out of the loop, and continue skips the current iteration.
case
Use case esac to create conditional statements.
case $1 in 1) echo 'You selected 1' ;; 2) echo 'You selected 2' ;; 3) echo 'You selected 3' ;; 4) echo 'You selected 4' ;; *) echo 'You did not enter a number between 1 and 4' ;;esac
case "$2" in "muxiao") echo "muxiao" ;; "blog") echo "blog" ;; "hello") echo "hello" ;;esacFunctions
function function_name() { echo "hello world"}
function_nameWhen calling a function, you don’t need to add parentheses; likewise, if you need to pass parameters, you don’t need to add them when defining the function.
function function_name() { echo "$1"}
function_name "hello world"You can see that passing parameters to functions in a script is the same as passing parameters on the console. If the function needs to return a value, then you need to use the return keyword.
function function_name() { return $1}
a=$(function_name 1)echo $aCalling Scripts from Each Other
Use source ./file.sh to call a script, but note that you need to use an absolute or relative path.
source ./file1.shsource /path/to/file2.shThis way you can use the variables in file1.sh and file2.sh and simultaneously run the scripts in file1.sh and file2.sh (it’s as if the scripts in file1.sh and file2.sh were copied here).