Bash 脚本入门
Alex Scriven
Data Scientist
当存在多个或复杂条件时,CASE 比 IF 更高效。
假设要测试以下条件与操作:
sydney,则移到目录 /sydneymelbourne 或 brisbane,则删除canberra,则重命名为 IMPORTANT_filename,其中 filename 为原文件名也可以像这样写多个 IF:
grep 作为条件判断。if grep -q 'sydney' $1; then
mv $1 sydney/
fi
if grep -q 'melbourne|brisbane' $1; then
rm $1
fi
if grep -q 'canberra' $1; then
mv $1 "IMPORTANT_$1"
fi
PATTERN 可用正则。如 Air* 表示"以 Air 开头",*hat* 表示"包含 hat"。CASE 基本格式:
case 'STRINGVAR' inPATTERN1) COMMAND1;; PATTERN2) COMMAND2;;
*) DEFAULT COMMAND;;
esac 最后一行是 esac
CASE 基本格式:
case 'STRING' in PATTERN1) COMMAND1;; PATTERN2) COMMAND2;;*) DEFAULT COMMAND;;esac
我们之前的 IF 语句:
if grep -q 'sydney' $1; then
mv $1 sydney/
fi
if grep -q 'melbourne|brisbane' $1; then
rm $1
fi
if grep -q 'canberra' $1; then
mv $1 "IMPORTANT_$1"
fi
我们的新 CASE 语句:
case $(cat $1) in*sydney*) mv $1 sydney/ ;; *melbourne*|*brisbane*) rm $1 ;; *canberra*) mv $1 "IMPORTANT_$1" ;;*) echo "No cities found" ;; esac
Bash 脚本入门