1. 变量
VARNAME=value
export VARNAME=value:导出环境变量
输出变量:
echo $VARNAME
echo ${VARNAME}
2. 命令代换:'或$()
DATE=`date`
DATE=$(date)
3. 算术代换:$(())
VAR=300
VAR2=$(($VAR+3))
4. 单引号
保留字符串的字面值
VAR=aaa
echo '$VAR' --> 输出 $VAR
5. 双引号
会把变量转换成实际值
echo "$VAR" --> 输出aaa
6. 位置参数
$0:shell程序名
$1,$2,...:程序参数
$#:参数个数(不包括程序名)
$@:参数列表,可以用于for in中
$$:当前shell的进程号
7. 条件语句
- if [ -f "filename" ]; then
- ...
- elif [ -z "$xx" ]; then
- ...
- fi
8. for循环
- for VAR in list; do
- ...
- done
- e.g.,
- hrs="00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23"
- for hr in $hrs; do
- echo $hr
- done
- for((i=0;i<10;i++)); do
- ...
- done
9. while循环
- while [ expr ]; do
- ...
- done
- i=1
- while [ $i -lt 10 ]
- do
- sed -n "${i}p" 111.txt
- i=$(($i+1)) 必须双层括号
- done
跳出循环:continue; 和break;
10. 字符串相关
替换:
${VAR/str1/replacement}
e.g.
a=aabbcc
echo ${a/aa/bb} -->输出bbbbcc
比较:
- if [[ "$a" < "$b" ]; then
- ...
- fi
截取:
${str:position:length}
#!/bin/sh test=testValue echo ${test} DATE=`date` DATE2=$(date) echo $DATE echo $DATE2 VAR=300 VAR2=$(($VAR+3)) echo $VAR echo $VAR2 VAR=aaaa echo '$VAR' echo "$VAR" echo $0 echo $1 echo $# echo $@ echo $$ for i in $@; do echo $i done for((i=0;i<$#;i++));do echo $(($i+4)) done i=1 while [ $i -lt 10 ] do sed -n "${i}p" 111.txt i=$(($i+1)) done a=aaaabbbbcccc echo ${a/b/d} #从第0个开始 echo ${a:0:4}
#!/bin/sh for file in ./* do if test -f $file then echo $file is file elif test -d $file then echo $file is dir fi done # for do for file in ./* do # if then if test -f $file then echo $file is file else echo $file is dir fi done
#!/bin/sh if test -d ./ ; then for i in ./*.sh; do if test -r $i ; then # 比较字符相等 if [ "$i" != "./lianxi3.sh" ] ; then . $i fi fi done unset i fi
判断中与或使用 &&,||
#!/bin/sh a="avalue" if [ -n $a ] && [[ 1 -eq 1 ]] && [[ $a == "avaalue" ]]; then echo 'yes' else echo 'no' fi if [[ $a == "aavalue" ]] ;then echo 'y' else echo 'no' fi
#!/bin/sh if [ ! -d "/etc" ];then echo '/etc is not dir' else echo '/etc is dir' fi if [ -d "/etc" ] && [ -f "/etc/passw" ] ;then echo 'both is Y' else echo 'one is not Y' fi if [ -d "/etc" ] || [ -f "/etc/passwd" ]; then echo 'one is Y' else echo 'all is not Y;' fi
#/bin/sh FILENAME="$1" PWD=`pwd` for file in `cat $FILENAME` do dir=`dirname $file` base=`basename $file` dir="$PWD""$dir" targetFile="$dir""/""$base" echo $dir echo $base echo $dir if [ -d $dir ];then echo $dir else mkdir -p $dir fi cp -r $file $targetFile done