linux shell脚本

不论是哪一种Shell,它最主要功能都是解译使用者的指令。类似windows中.bat

UNIX常用shell:
http://blog.csdn.net/zhangxuechao_/article/details/72235721

运行方法

# sh file.sh
# ./file.sh
# source file.sh

变量

所有的变量都由字符串组成,并且您不需要对变量进行声明

$#:命令行参数的数目
$?:前一个命令的返回码(0表示没有错误)
$0:程序名
$$:当前进程ID
$*:命令行参数
$@:命令行参数

$*和$@区别:
http://blog.csdn.net/zhangxuechao_/article/details/72956746

变量名和文字混淆

hel="hel"
echo "this is ${hel}lo"

:=附近无空格

条件判断

字符串

str1 = str2     //相等为真
str1 != str2    //不等为真
-n str1         //非空为真
-z str1         //空为真
str1            //非空为真

数字

int1 -eq int2   //相等为真
int1 -ne int2   //不等为真
int1 -gt int2   //int1大于int2为真
int1 -ge int2   //int1大于等于int2为真
int1 -lt int2   //int1小于int2为真
int1 -le int2   //int1小于等于int2为真

文件

-r file         //可读为真 
-w file         //可写为真 
-x file         //可执行为真 
-f file         //为文件为真 
-d file         //为目录为真 
-c file         //为字符文件为真 
-b file         //为块文件为真 
-s file         //大小非0为真 
-t file         //当文件描述符(默认为1)指定的设备为终端时为真

逻辑判断

-a              //与 
-o              //或 
!               //非

语法

if [ $str1 = $str2 ]
    ...
fi

:[]附近有空格,=附近有空格

流程控制

if

if 条件; then  
    ...  
else  
    ...  
fi  

for

for i in 列表; do
    ...  
done  

while

while 条件; do  
    ...
done  

case

case i in
pattern 1)
    ...
pattern 1)
    ...
*)
    ...
esac

here文档

<< EOF
    ...
EOF

EOF可以替换成其他字符

<<- EOF
    ...
EOF

不带缩进格式

调试

# sh -x test.sh 
# sh -n test.sh 

-n:并不执行脚本,只是返回所有的语法错误

FTP上传脚本

#!/bin/sh
ftp -ivn $ipaddr << EOF
user $username $password
binary
hash
prompt
put $filename
bye
EOF

-i:关闭多文件传输过程中的交互提示,所以不会再有让用户输入用户名和密码的提示
prompt:交互模式开关

原文地址:https://www.cnblogs.com/zhangxuechao/p/11709661.html