shell 脚本看起来是这样的
#!/bin/env bash
# def var
DATE=`date`
LOG_FILE=`date +%Y%m%d`.log
# use var
echo $DATE
echo "$DATE"
echo ${DATE} # ${} 还有额外的用法
# 注意不加 "" 的引用和有 "" 是不一样的
HELLO="AB C D"
echo $HELLO # AB C D
echo "$HELLO" # AB C D
exit $?
- 脚本解释行
#! path
用于表明解释该文本的解释器,类似的用法还有#!/usr/bin/python
#!/bin/lua
分支语句
if EXPRESSION
then
echo "do something"
fi
# or
if EXPRESSION; then
echo "do something"
fi
# muti branches
if EXPRESSION
then
echo "do something 1"
elif EXPRESSION
then
echo "do something 2"
else
echo "do something 3"
fi
# switch...case
case "$variable" in
"$condition1" )
command...
;;
"$condition2" )
command...
;;
esac
# Example 眼熟?ABS 上搬过来的
case "$Keypress" in
[[:lower:]] ) echo "Lowercase letter";;
[[:upper:]] ) echo "Uppercase letter";;
[0-9] ) echo "Digit";;
* ) echo "Punctuation, whitespace, or other";;
esac
循环语句
# 范围语句 for
for arg in [list]
do
command(s)...
done
# 例子
for num in 1 2 3 4 5 6
do
echo "$num"
done
for num in `seq 6`
do
echo "$num"
done
for num in {1..6}
do
echo -n "$num "
done
# C 风格
LIMIT=10
for ((a=1, b=1; a <= LIMIT ; ++a, ++b))
do # The comma concatenates operations.
echo -n "$a-$b "
done
# while 语句
while [ condition ]
do
command(s)...
done
# Example
var0=0
LIMIT=10
while [ "$var0" -lt "$LIMIT" ]
do
echo -n "$var0 "
var0=`expr $var0 + 1`
done
# break / continue
break n # 跳出第 n 层循环
continue n # 跳出第 n 层循环,并继续
ing...