Zsh基本语法篇

102 阅读1分钟

变量定义

#定义变量
name="John"
age=25
#使用变量
echo $name
echo "Age: $age"
#只读变量
readnly PI=3.14
#删除变量
unset name

字符串操作

#单引号字符串(不解析变量):
str='Hello, $name'
echo $str  # 输出: Hello, $name
双引号字符串(解析变量):
str="Hello, $name"
echo $str  # 输出: Hello, John
字符串拼接
greeting="Hello, "$name"!"
echo $greeting

数组

数组定义
fruits=("Apple" "Banana" "Cherry")
访问数组元素
echo ${fruits[1]}  # 输出: Banana
访问所有元素
echo ${fruits[@]}
数组长度
echo ${#fruits[@]}  # 输出: 3
添加元素
fruits+=("Orange")

条件判断

if语句

if [[ $age -gt 18 ]]; then
  echo "You are an adult."
else
  echo "You are a minor."
fi

比较运算符:

  • 数值比较:-eq(等于)、-ne(不等于)、-gt(大于)、-lt(小于)
  • 字符串比较:=(等于)、!=(不等于)
  • 文件测试:-e(文件存在)、-d(是目录)、-f(是文件)

case语句

case $fruit in
    "apple")
        echo "it's a apple"
        ;;
    "banana")
        echo "it's a banana"
        ;;
    *)
        echo "unknow fruit"
        ;;
esac

循环

for循环

for i in {1..5}; do
  echo "Count: $i"
done

while循环

count=1
while [[ $count -le 5 ]]; do
  echo "Count: $count"
  ((count++))
done

until循环

count=1
until [[ $count -gt 5 ]]; do
  echo "Count: $count"
  ((count++))
done

函数

#定义
greet() {
  echo "Hello, $1!"
}
#调用
greet "John"
#返回值
add() {
  return $(($1 + $2))
}
add 3 5
echo $? 

输入与输出

#读取用户输入 echo "Enter your name:" read name echo "Hello, $name!" #输出到文件 echo "Hello, World!" > output.txt #追加到文件 echo "Hello again!" >> output.txt

通配符和扩展

  1. 通配符
ls *.txt       # 列出所有 .txt 文件
ls **/*.txt    # 递归列出所有子目录中的 .txt 文件
  1. 大括号扩展
echo {1..5}    # 输出: 1 2 3 4 5
echo {A,B,C}   # 输出: A B C

命令替换

current_date=$(date)
echo "Today is $current_date"

获取脚本参数

echo "Script name: $0"
echo "First argument: $1"
echo "All arguments: $@"
echo "Number of arguments: $#"