第一个shell脚本
1,建立shell脚本
打开文本编辑器vi/vim,新建test.sh,输入如下代码:
#!/bin/bash
echo "Hello World !"
表示脚本需要的解释器 #!
2,运行shell脚本的两种方法
1,作为可执行程序
chmod +x ./test.sh #使脚本具有执行权限
./test.sh
如果直接写test.sh 系统回去PATH里寻找,./ 指定当前目录
2,作为解释器参数
运行解释器
/bin/sh test.sh
Shell变量
定义变量以及给变量赋值不能以
开头使用变量加
开
头
使
用
变
量
加
变量名外加{}是为了帮助解释器识别变量边界。
可以用readonly命令将变量定义为只读(不可写,不可执行)
删除变量 unset variable_name
变量类型:
1,局部变量:在脚本或者命令中定义,在当前shell中有效,其他shell不能访问局部变量
2,环境变量:所有程序均可访问环境变量,
3,shell变量:由shell程序设置的特殊变量,有一部分为环境变量,一部分为局部变量。
shell字符串
可用单引号、双引号、无引号
单引号:任何字符原样输出,字符串内变量无效,不能有转义字符
双引号:其中可以出现变量和转义字符
获取字符串的长度:
string="abcd"
echo ${#string}
提取子字符串`
string="runoob is a great site"
echo ${string:1:4} #输出unoo
查找子字符串
string="runoob is a great site"
echo `expr index "$string" io` 输出4
`为反引号注意
shell数组
定义数组
属组名=(值1 2 3 4…)
无多维数组
读取数组格式
${属组名[下标]}
符号@可以获取数组中所有元素
获取数组长度方法与字符串相同
length=${#array_name[@或者* n为获取单个元素]}
shell注释:
以#开头的
或者
:<
echo "the example of shell's parameter deliver:";
echo "the filename of execuse is : $0";
echo "the first parameter is $1";
echo "the second parameter is $2";
echo "the third parameter is $3";
结果为
root@ubuntu:~# ./canshu.sh 1 2 string
the example of shell's parameter deliver:
the filename of execuse is : ./canshu.sh
the first parameter is 1
the second parameter is 2
the third parameter is string
几个特殊字符用来处理参数:
shell数组部分不在赘述
先写到这吧,感觉后面的都挺简单的