shell脚本入门基础知识

shell 脚本的第一行

#!/bin/bash
#!/bin/sh		其实,sh是bash的一个软链接 sh -> bash 

变量,字母下划线开头(好像是没有类型的)

#普通变量
var1=nihao		#不能有空格
echo $var1 		#使用$表示变量

#环境变量

echo $JAVA_HOME 	#全局变量用全大写
/etc/profil/e         	#全局环境变量存储位置

#用户环境变量
/home/cen/.bash_profile 	#编辑文件后需要用source命令更新

#删除变量
unset 变量名

位置参量,用于传递参数

#定义位置参量
echo "Hello $1 !!" 		#用$1,$2....${10},${11} ...表示接受到的第n个参数
#$0 表示当前脚本的文件名
#$# 表示传入参数个数
#$? 上一个命令的状态嘛,有一些依赖关系必须知道之前的执行情况

#传入参数
./xxx.sh 参数一 参数二 		#用空格分隔位置参数,如果位置参数有空格,使用"hello world!"

数组

#数组定义
arr=(zhangsan lisi wangwu)

#数组引用
echo ${arr[0]} 		#zhangsan
echo ${arr[*]} 		#zhangsan lisi wangwu 
echo ${#arr{*}} 	#3

查看时间

#当前时间
date1=$(date)

#一天前
date2=$(date --date='1 days age')
date2=$(date --date='1 days')

#一天后
date3=$(date --date='1 days')
date3=$(date --date='-1 days ago')

判断test -e filename 或者 [ -e filename ] []两端一定要有空格

#文件类型判断
#-e 	判断文件是否exist
#-f 	是否为file 
#-d 	是否为dir

#权限判断
#-r 	可读
#-w 	可写
#-x 	可执行

#判断整数
#-eq 	equal			相等
#-ne 	not equal		不相等
#-gt 	greater than	大于
#-lt 	less than		小于

#判断字符串
#-z 	zero			空字符串
#-n 	not 			非空
#=/==   				相等
#!=						不等

if语句

if [ -f "filename" ] && [ -e "filename" ] ; then 
	#todo...
	#todo...
elif [ -e "filename" ]
	#todo...
else
	#todo...
fi

for循环

#for循环(1)
for var in 1 2 3 4 5
do
	#todo...
done
#for循环(2)
n=10
sum=0
sum2=0
for((i=0;i<${n};i=i+1))
do
	sum=$((${sum1}+$(i))) 		#正儿八经的加法
	sum2=${sum2}+${i} 	#字符串拼接 
done

while循环

#正经点while
while [ -e "filename" ]
do
	#todo...
done
#当到型while
until [ -e "filename" ]
do
	#todo...
done

#配合cat和管道函数的while(不会应用场景)
cat a.txt | while read line

神奇的$符号

${变量}
$(可执行语句) 		#(1+1)带括号的才是可执行语句

执行shell脚本的四种方式

    $/home/user/xxx.sh
    $./xxx.sh        
    $. xxx.sh      
    $sh xxx.sh   

四种方式区别

原文地址:https://www.cnblogs.com/cenzhongman/p/6920994.html