shell 编程

1,shell脚本程序是指以文件的形式存放Linux命令集合,该文件能够被shell解释执行

文件里面通常包含Linux 命令,shell命令,流程控制语句,注释,通常是.sh 作为后缀名

2,第一行指定程序来编译和执行脚本

#! /bin/bash      #! /bin/sh

注释行:使用(#) 符号

3,变量

变量名必须以字母或者下划线开头,后面可以跟字母数字下划线。任何其他字符都标志者变量名结束

4,变量类型

本地变量:只在创建的shell 程序中可以使用

环境变量:所有的用户进程中可以使用,也称为全局变量,例如$JAVA_HOME,按照惯例,需要大写

5,设置当前用户的环境变量

在当前用户的主目录下,在 .bash_profile 下创建当前用户的全局变量

6,位置参量

特殊的内置变量,通常是被shell 脚本用来从命令行接受的参数,或者被函数用来保存传递它的参数

### test.sh shell脚本
#! /bin/bash echo " hello world $1 $2 !!!"
./ test.sh my shell           ====            hello world my shell !!!
. test.sh  your shell         ====            hello world your shell !!!    . 当前目录下的test 文件
sh test.sh our shell          ====            hello world our shell !!!     sh+程序名     
sh test.sh "our shell" ok ==== hello world our shell ok 位置参量有空格,需要用引号

$0  当前脚本的文件名

$1-$9 第一个到第九个位置参量

${10} 第十个位置参量,类似往下推

$# 位置参量的个数

$* 以但字符串显示所有的位置参量

$@ 无引号等同于$*

$$ 脚本运行的当前进程号

$! 最后一个后台运行的进程的进程号

$? 显示前面最后一个命令的退出状态,0 表示没有错误,其他任何表示有错误 

7,shell 编程中申明一个变量

name=chris

    申明一个数组

arr=(name1 name2 name3)

echo ${arr[0]}  回显出第一个

echo $(arr[*])   回显出所有

echo $(#arr[*]) 回显出个数

arr[0]=tom       重新赋值

8, date

date + %Y-%m-%d

date --date='2 days ago' +  %Y-%m-%d      //2天前

 9,shell 条件判断

test -e filename 文件是否存在 if [-e filename]   [] 相当于test

test -f filename  是否是file

test -d filename 是否是directory

test -r filename 是否具有可读权限

test -w filename 是否具有可写的权限

test -x filename 是否具有可执行的权限

整数之间判断

test n1 -eq n2  两数值相等(equal)

test n1 -nq n2  两数值不相等(not equal)

test n1 -gt n2   n1大于n2 (greater than)

test n1 -lt n2    n1小于n2 (less than)

test n1 -ge n2  n1大于等于n2(greater than or equal)

test n1 -le n2   n1小于等于n2(less than or equal)

字符串判断

test -z string   字符串长度是否为0,空串返回true

test -n string   字符串长度是否大于0,空串返回false , -n 可以省略

test str1 = str2 判断str1是否等于str2,相等,返回true

test str1 != str2 判断str1是否不等于str2,不相等,返回true

if 判断

if condition
then
    command1 
    command2
    ...
    commandN
else
    command
fi


if condition1
then
    command1
elif condition2 
then 
    command2
else
    commandN
fi


a=10
b=20
if [ $a == $b ]
then
   echo "a 等于 b"
elif [ $a -gt $b ]
then
   echo "a 大于 b"
elif [ $a -lt $b ]
then
   echo "a 小于 b"
else
   echo "没有符合的条件"
fi


while 语句

while condition
do
    command
done

int=1
while(( $int<=5 ))
do
    echo $int
    let "int++"
done

for 循环

for var in item1 item2 ... itemN
do
    command1
    command2
    ...
    commandN
done


for loop in 1 2 3 4 5
do
    echo "The value is: $loop"
done

  

原文地址:https://www.cnblogs.com/pickKnow/p/10676532.html