linux之shell编程shell基础

shell文件的结构:

  1.   #! 指定要执行脚本的shell语言类型
  2.   #  表示这是一行注释代码
  3.   命令和一些控制结构的语句(一般要些命令的绝对路径),这些命令与在控制台输入的命令一样。

创建shell程序的步骤:

  1. 创建一个符合shell格式的文件(命令和控制结果)。
  2. 为文件添加可执行的权限
  3. 执行shell文件

变量:变量有两种:临时变量和永久变量

  临时变量:用户自定义的变量,字母,数字,下划线组成,区分大小写,没有长度限制,使用$来调用变量

  永久变量:环境变量(PATH,LANG,PS1)

使用$来调用变量,如:echo $PATH,即回显出系统的环境变量值。

变量的定义一般使用大写的字母,单引号和双引号的区别

[root@localhost ~]# echo `date`
2013年 02月 23日 星期六 23:06:20 CST
[root@localhost ~]# TIME=$(date +%F)
[root@localhost ~]# echo $TIME
2013-02-23
[root@localhost ~]# DATE=$TIME
[root@localhost ~]# echo $DATE
2013-02-23
[root@localhost ~]# A="today is $DATE"
[root@localhost ~]# echo $A
today is 2013-02-23
[root@localhost ~]# A='this is $DATE'
[root@localhost ~]# echo $A
this is $DATE

set命令查看系统中所有已经定义的变量

使用unset xxx(变量名)即可删除变量

特殊变量:位置变量和特使变量

  位置变量:ls -l file1 file2 file3(ls -l为$0,flien为$n)

  特殊变量:$*:执行这个命令的所有的参数

       $#:执行这个命令的参数的个数

       $$:执行这个命令的PID

       $!:执行上一个后台命令的PID

       $?:执行上一个命令的返回值

example:

[root@localhost ~]# mkdir /shell
[root@localhost ~]# cd /shell
[root@localhost shell]# touch special.var
[root@localhost shell]# vim special.var

使用vim在special.var文件中输入以下内容
#!/bin/sh
# test special variable
# Usage: sh special.var file01 file02

echo '参数的个数'
echo '$# is:' $#
echo '参数的内容'
echo '$* is' $*
echo '执行上一个命令的返回值(0表示执行成功,非0表示执行失败)'
echo '$? is' $?
echo '执行上一个命令的PID'
echo '$$ is' $$
echo '位置变量'
echo '$0 is' $0
保存退出

[root@localhost shell]# sh special.var file02 file03 file04
参数的个数
$# is: 3
参数的内容
$* is file02 file03 file04
执行上一个命令的返回值(0表示执行成功,非0表示执行失败)
$? is 0
执行上一个命令的PID
$$ is 6109
位置变量
$0 is special.var
[root@localhost shell]#
[root@localhost shell]# sh special.var file02 file03 file04 file8
参数的个数
$# is: 4
参数的内容
$* is file02 file03 file04 file8
执行上一个命令的返回值(0表示执行成功,非0表示执行失败)
$? is 0
执行上一个命令的PID
$$ is 6101
位置变量
$0 is special.var
 
shell命令:

read:

在read文件中输入

#!/bin/sh
read first second third
echo "the first parameter is $first"
echo "the second parameter is $second"
echo "the second parameter is $second"

[root@localhost shell]# sh read
100 200 300
the first parameter is 100
the second parameter is 200
the second parameter is 200

执行脚本加入-x参数显示脚本执行的过程
[root@localhost shell]# sh -x read
+ read first second third
1 2 3
+ echo 'the first parameter is 1'
the first parameter is 1
+ echo 'the second parameter is 2'
the second parameter is 2
+ echo 'the second parameter is 2'
the second parameter is 2
[root@localhost shell]#

expr命令:

[root@localhost shell]# expr 3+5
3+5
[root@localhost shell]# expr 3 + 5
8
[root@localhost shell]# expr 10 / 3
3
[root@localhost shell]# expr 10 \* 3
30


原文地址:https://www.cnblogs.com/charleszhang1988/p/shell.html