bash-linux

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Bash Linux Patterns

Bash Linux 终端实用模式

Essential patterns for Bash on Linux/macOS.

适用于Linux/macOS的Bash实用模式。

1. Operator Syntax

1. 操作符语法

Chaining Commands

命令链式执行

OperatorMeaningExample
;
Run sequentially
cmd1; cmd2
&&
Run if previous succeeded
npm install && npm run dev
||
Run if previous failed
npm test || echo "Tests failed"
|
Pipe output
ls | grep ".js"

操作符含义示例
;
按顺序执行
cmd1; cmd2
&&
前一个命令执行成功后再运行
npm install && npm run dev
||
前一个命令执行失败后再运行
npm test || echo "Tests failed"
|
管道输出
ls | grep ".js"

2. File Operations

2. 文件操作

Essential Commands

核心命令

TaskCommand
List all
ls -la
Find files
find . -name "*.js" -type f
File content
cat file.txt
First N lines
head -n 20 file.txt
Last N lines
tail -n 20 file.txt
Follow log
tail -f log.txt
Search in files
grep -r "pattern" --include="*.js"
File size
du -sh *
Disk usage
df -h

任务命令
列出所有文件
ls -la
查找文件
find . -name "*.js" -type f
查看文件内容
cat file.txt
查看前N行
head -n 20 file.txt
查看后N行
tail -n 20 file.txt
实时跟踪日志
tail -f log.txt
在文件中搜索内容
grep -r "pattern" --include="*.js"
查看文件大小
du -sh *
查看磁盘使用情况
df -h

3. Process Management

3. 进程管理

TaskCommand
List processes
ps aux
Find by name
ps aux | grep node
Kill by PID
kill -9 <PID>
Find port user
lsof -i :3000
Kill port
kill -9 $(lsof -t -i :3000)
Background
npm run dev &
Jobs
jobs -l
Bring to front
fg %1

任务命令
列出所有进程
ps aux
按名称查找进程
ps aux | grep node
通过PID杀死进程
kill -9 <PID>
查找端口占用者
lsof -i :3000
杀死端口占用进程
kill -9 $(lsof -t -i :3000)
后台运行命令
npm run dev &
查看后台任务
jobs -l
将后台任务调至前台
fg %1

4. Text Processing

4. 文本处理

Core Tools

核心工具

ToolPurposeExample
grep
Search
grep -rn "TODO" src/
sed
Replace
sed -i 's/old/new/g' file.txt
awk
Extract columns
awk '{print $1}' file.txt
cut
Cut fields
cut -d',' -f1 data.csv
sort
Sort lines
sort -u file.txt
uniq
Unique lines
sort file.txt | uniq -c
wc
Count
wc -l file.txt

工具用途示例
grep
内容搜索
grep -rn "TODO" src/
sed
内容替换
sed -i 's/old/new/g' file.txt
awk
提取列
awk '{print $1}' file.txt
cut
截取字段
cut -d',' -f1 data.csv
sort
行排序
sort -u file.txt
uniq
去重行
sort file.txt | uniq -c
wc
统计
wc -l file.txt

5. Environment Variables

5. 环境变量

TaskCommand
View all
env
or
printenv
View one
echo $PATH
Set temporary
export VAR="value"
Set in script
VAR="value" command
Add to PATH
export PATH="$PATH:/new/path"

任务命令
查看所有环境变量
env
printenv
查看单个环境变量
echo $PATH
设置临时环境变量
export VAR="value"
在脚本中设置环境变量
VAR="value" command
添加路径到PATH
export PATH="$PATH:/new/path"

6. Network

6. 网络操作

TaskCommand
Download
curl -O https://example.com/file
API request
curl -X GET https://api.example.com
POST JSON
curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' URL
Check port
nc -zv localhost 3000
Network info
ifconfig
or
ip addr

任务命令
下载文件
curl -O https://example.com/file
API请求
curl -X GET https://api.example.com
发送JSON格式POST请求
curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' URL
检查端口连通性
nc -zv localhost 3000
查看网络信息
ifconfig
ip addr

7. Script Template

7. 脚本模板

bash
#!/bin/bash
set -euo pipefail  # Exit on error, undefined var, pipe fail
bash
#!/bin/bash
set -euo pipefail  # Exit on error, undefined var, pipe fail

Colors (optional)

Colors (optional)

RED='\033[0;31m' GREEN='\033[0;32m' NC='\033[0m'
RED='\033[0;31m' GREEN='\033[0;32m' NC='\033[0m'

Script directory

Script directory

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

Functions

Functions

log_info() { echo -e "${GREEN}[INFO]${NC} $1"; } log_error() { echo -e "${RED}[ERROR]${NC} $1" >&2; }
log_info() { echo -e "${GREEN}[INFO]${NC} $1"; } log_error() { echo -e "${RED}[ERROR]${NC} $1" >&2; }

Main

Main

main() { log_info "Starting..." # Your logic here log_info "Done!" }
main "$@"

---
main() { log_info "Starting..." # Your logic here log_info "Done!" }
main "$@"

---

8. Common Patterns

8. 常用模式

Check if command exists

检查命令是否存在

bash
if command -v node &> /dev/null; then
    echo "Node is installed"
fi
bash
if command -v node &> /dev/null; then
    echo "Node is installed"
fi

Default variable value

变量默认值

bash
NAME=${1:-"default_value"}
bash
NAME=${1:-"default_value"}

Read file line by line

逐行读取文件

bash
while IFS= read -r line; do
    echo "$line"
done < file.txt
bash
while IFS= read -r line; do
    echo "$line"
done < file.txt

Loop over files

遍历文件

bash
for file in *.js; do
    echo "Processing $file"
done

bash
for file in *.js; do
    echo "Processing $file"
done

9. Differences from PowerShell

9. 与PowerShell的差异

TaskPowerShellBash
List files
Get-ChildItem
ls -la
Find files
Get-ChildItem -Recurse
find . -type f
Environment
$env:VAR
$VAR
String concat
"$a$b"
"$a$b"
(same)
Null check
if ($x)
if [ -n "$x" ]
PipelineObject-basedText-based

任务PowerShellBash
列出文件
Get-ChildItem
ls -la
查找文件
Get-ChildItem -Recurse
find . -type f
环境变量
$env:VAR
$VAR
字符串拼接
"$a$b"
"$a$b"
(相同)
空值检查
if ($x)
if [ -n "$x" ]
管道基于对象基于文本

10. Error Handling

10. 错误处理

Set options

设置选项

bash
set -e          # Exit on error
set -u          # Exit on undefined variable
set -o pipefail # Exit on pipe failure
set -x          # Debug: print commands
bash
set -e          # Exit on error
set -u          # Exit on undefined variable
set -o pipefail # Exit on pipe failure
set -x          # Debug: print commands

Trap for cleanup

清理操作陷阱

bash
cleanup() {
    echo "Cleaning up..."
    rm -f /tmp/tempfile
}
trap cleanup EXIT

Remember: Bash is text-based. Use
&&
for success chains,
set -e
for safety, and quote your variables!
bash
cleanup() {
    echo "Cleaning up..."
    rm -f /tmp/tempfile
}
trap cleanup EXIT

注意: Bash是基于文本的工具。使用
&&
实现成功链式执行,使用
set -e
提升脚本安全性,记得给变量添加引号!