shell基础范例
shell 常用写法示例,仅供参考。
文件操作
路径获取
1 2 3 4 5 6 7 8
   | # 获取文件绝对路径 realpath
  # 获取当前文件所在目录 dirname
  # 分割字符串 echo "1,2,3" | cut -d',' -f2 # 输出 2
   | 
 
文件处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
   | # 检查文件是否存在 if [ -f "filename" ]; then     echo "File exists" else     echo "File does not exist" fi
  # 检查目录是否存在,不存在则创建 if [ ! -d "dirname" ]; then     mkdir dirname fi
  # 复制文件 cp sourcefile destfile
  # 移动文件 mv sourcefile destfile
  # 删除文件 rm filename
  # 删除目录及内容 rm -rf dirname
   | 
 
帮助信息
usage函数中自定义输出提示内容
脚本开头写法
提示函数
判断执行脚本有没有带“-help或者-h”,如果有则执行usage函数
1 2 3 4 5 6 7 8 9 10 11
   | usage() {     echo "Usage: $0 [options]"     echo "Options:"     echo "  -h, --help    Display this help message"     echo "  -v, --version Display version information" }
  if echo $@|grep -wqE "help|-h"; then     usage 	exit 0 fi
  | 
 
脚本调试模式
功能:调试模式和防止脚本执行出错
1 2 3 4 5
   | # 当执行脚本时,如果执行命令出错,直接退出脚本 set -e
  # 设置脚本为调试模式,显示每条命令解释器以及参数 set -x
   | 
 
输出不同颜色
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
   | # 定义颜色变量 RED='\e[31m' GREEN='\e[32m' YELLOW='\e[33m' BLUE='\e[34m' PURPLE='\e[35m' CYAN='\e[36m' RESET='\e[0m'
  # 使用颜色输出 echo -e "${RED}This is red text${RESET}" echo -e "${GREEN}This is green text${RESET}"
  # 蓝色 ~$  echo -e "\e[36m lll \e[0m" # 红色 ~$ echo -e "\e[31m lll \e[0m"
 
   | 
 
函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
   | # 定义函数 greet() {     echo "Hello, $1!" }
  # 调用函数 greet "World"
  # 带返回值的函数 add() {     local sum=$(( $1 + $2 ))     echo $sum }
  result=$(add 3 5) echo "Result: $result"
  # 带默认参数的函数 greet_default() {     local name=${1:-Guest}     echo "Hello, $name!" }
  greet_default "Alice" greet_default
   | 
 
错误处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
   | # 捕获错误并处理 trap 'echo "Error occurred at line $LINENO"' ERR
  # 自定义错误处理函数 handle_error() {     local exit_code=$?     local line_number=$1     echo "Error occurred at line $line_number with exit code $exit_code"     exit 1 }
  trap 'handle_error $LINENO' ERR
  # 检查命令是否成功 if ! command -v some_command >/dev/null 2>&1; then     echo "some_command not found"     exit 1 fi
   | 
 
进程管理
1 2 3 4 5 6 7 8 9 10 11 12
   | # 查找并杀死进程 pkill -f "process_name"
  # 获取进程 ID pid=$(pgrep -f "process_name")
  # 检查进程是否存在 if pgrep -f "process_name" >/dev/null 2>&1; then     echo "Process is running" else     echo "Process is not running" fi
   | 
 
日志自定义
1 2 3 4 5 6 7 8 9 10 11
   | # 定义日志函数 log() {     local level=$1     local message=$2     echo "$(date +"%Y-%m-%d %H:%M:%S") [$level] $message" >> script.log }
  # 使用日志函数 log "INFO" "Script started" log "WARNING" "Low disk space" log "ERROR" "Failed to connect"
   | 
 
批量重命名
把当前所有jpg文件全部重新用mpic_n重命名
1 2 3 4 5 6 7 8
   | #!/bin/bash
  i=1 for file in ./*.jpg; do     new_name=$(printf "%03d.jpg" $i)     mv "$file" "mpic_$i.jpg"     let "i++" done
   | 
 
待续….