Linux Study Notes - MuxiaoWFSkip to main content
This page was machine-translated and may contain errors or omissions. / 本页面为机器翻译,可能存在错漏。

Linux Study Notes

Linux Study Notes Basic Linux Commands

Sun Mar 01 2026
2174 words · 13 minutes

Basic Linux Commands

Linux has no drive letters; all files are stored under the root directory.

  1. cd change directory
    • cd /home/user change to the specified directory
    • cd / change to the root directory
    • cd ../ change to the parent directory
    • cd ./ change to the current directory
    • cd ~ change to the user directory (for the root user, this is equivalent to cd /root)
    • cd - change to the previously jumped-to directory
  2. pwd show the current directory
  3. ls list files in the directory (only file names, no details)
    • ls -l list files in the directory in list form (with details, equivalent to ll)
    • ls -a list all files (including hidden files)
    • ls -al list all files in the directory in list form (with details, equivalent to -a -l)
    • ls /root list files in the specified directory (here, under root)
  4. mkdir create a directory (make directory)
    • mkdir dirname create a directory dirname in the current folder; mkdir /dirname creates dirname under the root directory
    • mkdir dirname1 dirname2 create directories dirname1 and dirname2 in the current folder
    • mkdir -p dirname1/dirname2 create directory dirname1/dirname2 in the current folder; -p means the parent directory dirname1 can be created
  5. touch create a file (the content appended afterward is the same as the mkdir command)
  6. echo output, same as print in other languages
    • echo "hello world" output hello world
    • echo "hello world" > file.txt create the file and write hello world (overwrite mode)
    • echo "hello world" >> file.txt create the file and write hello world (append mode)
    • echo $PATH output the value of the variable PATH
  7. cat, more, less, head, tail commands can all view file contents
    • cat file.txt output the contents of file.txt (all contents)
    • more file.txt output the contents of file.txt (displayed line by line, press Enter for the next line, q to quit, has a progress bar)
    • less file.txt output the contents of file.txt (displayed line by line, press Enter for the next line, q to quit, no progress bar)
    • head file.txt output the first 10 lines of file.txt (head -20 file.txt outputs the first 20 lines of file.txt)
    • tail file.txt output the last 10 lines of file.txt (tail -20 file.txt outputs the last 20 lines of file.txt)
    • tail -f file.txt continuously output the last 10 lines of file.txt (new content is appended to the output, commonly used to view log files)
  8. cp copy files or directories (copy)
    • cp file.txt /home/user copy file.txt to the specified directory
    • cp -r dirname /home/user copy directory dirname to the specified directory (-r means recursive copy, i.e., copy all files and subdirectories under the directory)
  9. mv move files or directories (move) cut
    • mv file.txt /home/user move file.txt to the specified directory
    • mv dirname /home/user move directory dirname to the specified directory
    • mv dirname1 dirname2 rename directory dirname1 to dirname2 (if dirname2 already exists, move the contents of dirname1 into dirname2; if it doesn’t exist, it’s equivalent to renaming)
  10. rm delete files or directories (remove)
    • rm file.txt delete file.txt
    • rm -r dirname delete directory dirname and its contents (-r means recursive delete)
    • rm -rf dirname delete directory dirname and its contents (-rf means recursive delete without confirmation prompt, force delete)
  11. vi file.txt edit file.txt
    • after entering the file, first press i to enter insert mode
    • after editing, press Esc to exit insert mode
    • in a non-other mode, enter :wq to save and quit (:w save, :q quit, :wq! force save and quit)
    • vim is also an editor that highlights code; it requires installing additional packages
  12. gzip, tar compress files
    • gzip file.txt compress file.txt (automatically generates file.txt.gz and deletes the source file)
    • gzip -d file.txt.gz decompress file.txt.gz (automatically deletes the source file)
    • gzip -k file.txt compress file.txt (does not delete the source file)
    • tar -zcvf file.tar.gz dirname compress directory dirname (automatically generates file.tar.gz and deletes the source directory)
    • tar -xvf file.tar -C /home/file decompress file.tar to the specified directory /home/file
    • zip is also a compression format, but requires installing additional packages
  13. yum install -y package install software on CentOS (apt install -y package on Ubuntu)
  14. grep search
    • grep -n string file.txt search for string string in file.txt and show line numbers (-n)
    • grep -i string file.txt search for string string in file.txt and ignore case (-i)
    • grep -v string file.txt search for string string in file.txt and invert the result (-v)
    • ls | grep string search for string string in the result of the ls command (ls can be replaced with other commands such as ps -ef, etc.)
  15. date show the current time
    • date -s "2026-01-03 12:00:00" set the time
    • ntpdate time1.aliyun.com synchronize the time
  16. scp remote copy of files (copy files between two machines)
    • scp file.txt user@remote_host:/home/user copy file file.txt to the remote host remote_host (logging in as user user) under /home/user
  17. chmod modify file permissions
    • chmod 755 file.txt modify the permissions of file.txt to 755 (owner can read/write/execute, others can read/execute)
    • chmod +x script.sh add execute permission to the script
    • chmod -R 755 dirname recursively modify permissions of all files in the directory
  18. chown modify file owner
    • chown user file.txt change the owner of file.txt to user user
    • chown user:group file.txt change the owner of file.txt to user and the group to group
    • chown -R hadoop:hadoop /usr/local/hadoop recursively modify the directory owner and group
  19. sudo execute a command with administrator privileges
    • sudo apt install package install a software package with administrator privileges
    • sudo -i switch to the root user (simulate a full login)
    • sudo -s switch to the root user’s shell
  20. su switch user
    • su - username switch to username user and load its environment variables
    • su username switch to username user but do not load environment variables
  21. ps view process status
    • ps -ef show detailed information of all processes
    • ps aux show detailed information of all processes (more commonly used)
    • ps -ef | grep java find all Java processes
  22. kill terminate a process
    • kill PID send the default signal to terminate the process (process ID required)
    • kill -9 PID force terminate the process
    • killall process_name terminate processes by process name
  23. top/htop monitor system resources in real time
    • top show process and resource usage in real time (press q to quit, P to sort by CPU, M to sort by memory)
    • htop a more intuitive monitoring tool (requires installation)
  24. df view disk space usage
    • df -h show disk usage in human-readable format (GB, MB, etc.)
    • df -T show the file system type
  25. du view directory size
    • du -sh dirname view the total size of directory dirname
    • du -ah dirname show the size of all files and directories under the directory
    • du --max-depth=1 dirname show the size of the first-level subdirectories under the directory
  26. find find files
    • find /home -name "file.txt" find a file named file.txt under /home
    • find . -type f -name "*.log" find all .log files under the current directory
    • find /var/log -mtime -7 find files modified within the last 7 days under /var/log
  27. ln create a symbolic link
    • ln -s /path/to/source /path/to/link create a symbolic link to the source file (similar to a Windows shortcut)
    • ln source link create a hard link
  28. netstat/ss view network connection status
    • netstat -tuln view all listening TCP and UDP ports
    • netstat -an | grep 8080 view the connection status of port 8080
    • ss -tuln a more modern command for viewing network status
  29. man view help documentation
    • man ls view detailed help for the ls command
    • man 5 passwd view the configuration file format description (5 indicates the section)
  30. jps view Java processes (bundled with the JDK)
    • jps show all Java processes and their process IDs
    • jps -l show the full class name or JAR file name
    • jps -v show 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).

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/bash as 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--))
  • let command: let a=1+2 or let 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.

Terminal window
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"
fi

Loop Statements

Use for in do done to create loop statements.

Terminal window
for i in 1 2 3 4 5; do
echo $i
done
for i in {1..10}; do
echo $i
done
arr=(a,b,c)
len = ${#arr[@]}
for ((i=0; i < $len; i++)); do
echo ${arr[$i]}
done
for i in $arr; do
echo $i
done

Write a script that grants permission to all files under a folder:

Terminal window
a=`ls $1`
for file in $a; do
chmod u+x $file
echo "Permission granted: $file"
done

Use while do done to create loop statements.

Terminal window
i=1
while [ $i -le 5 ]; do
echo $i
((i++))
done

Use until do done to create loop statements (loop until the condition is met).

Terminal window
i=1
until [ $i -gt 5 ]; do
echo $i
((i++))
done

Like 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.

Terminal window
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"
;;
esac

Functions

Terminal window
function function_name() {
echo "hello world"
}
function_name

When 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.

Terminal window
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.

Terminal window
function function_name() {
return $1
}
a=$(function_name 1)
echo $a

Calling Scripts from Each Other

Use source ./file.sh to call a script, but note that you need to use an absolute or relative path.

Terminal window
source ./file1.sh
source /path/to/file2.sh

This 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).


Thanks for reading! Follow me if you'd like~

Linux Study Notes

Sun Mar 01 2026
2174 words · 13 minutes
Cover
Sample track
Sample artist
Cover
Sample track
Sample artist
0:00 / 0:00