1.编写个人第一个shell脚本小程序:
[root@wenhaijin /]# mkdir shell [root@wenhaijin /]# cd shell/ [root@wenhaijin shell]# vim helloworld.sh #!/bin/bash #my first shell project echo "Hello World" ~ ~ ~ ~ "helloworld.sh" [New] 4L, 56C written
注意:linux
1.#!/bin/bash标志着如下内容是shell脚本(该行不是注释,这是固定写法)
2.#my first shell project是注释shell
3.echo "Hello World"是脚本的内容,注意不要加“!”,!在脚本中有特殊含义,若是要加“!”就写成echo 'Hello World!'小程序
2.shell脚本的执行
2.1 使用bash命令执行(不经常使用)
[root@wenhaijin shell]# bash helloworld.sh Hello World [root@wenhaijin shell]#
2.2 赋予执行权限,直接运行(通常都是经过这种方式执行)
[root@wenhaijin shell]# chmod 755 helloworld.sh [root@wenhaijin shell]# ./helloworld.sh Hello World [root@wenhaijin shell]#
3.将dos环境下的脚本转化为linx环境下的脚本
为何要将dos下的脚本转化为linux中的脚本呢,由于dos环境和linux环境对一些隐藏字符的处理方式不同,好比linux中的回车使用$符号表示的vim
### cat -A 表示查看详细信息,包括隐藏字符,这边的$实际上表明的就是linux中的回车 [root@wenhaijin shell]# cat -A helloworld.sh #!/bin/bash$ #my first shell project$ $ echo "Hello World"$
而在dos环境中,回车是用^M$表示,linux并不认识bash
[root@wenhaijin shell]# unix2dos helloworld.sh unix2dos: converting file helloworld.sh to DOS format ... [root@wenhaijin shell]# cat -A helloworld.sh #!/bin/bash^M$ #my first shell project^M$ ^M$ echo "Hello World"^M$ [root@wenhaijin shell]# ./helloworld.sh -bash: ./helloworld.sh: /bin/bash^M: bad interpreter: No such file or directory [root@wenhaijin shell]#
若linux系统中尚未dos2unix命令,可经过yum或者rpm包进行安装url
[root@wenhaijin shell]# yum -y install dos2unix Loaded plugins: security base | 3.7 kB 00:00 epel | 4.3 kB 00:00 epel/primary_db | 5.9 MB 00:01 extras | 3.4 kB 00:00 extras/primary_db | 37 kB 00:00 updates | 3.4 kB 00:00 updates/primary_db | 5.4 MB 00:00 Setting up Install Process Resolving Dependencies --> Running transaction check ---> Package dos2unix.x86_64 0:3.1-37.el6 will be installed --> Finished Dependency Resolution Dependencies Resolved ================================================================================ Package Arch Version Repository Size ================================================================================ Installing: dos2unix x86_64 3.1-37.el6 base 16 k Transaction Summary ================================================================================ Install 1 Package(s) Total download size: 16 k Installed size: 18 k Downloading Packages: dos2unix-3.1-37.el6.x86_64.rpm | 16 kB 00:00 Running rpm_check_debug Running Transaction Test Transaction Test Succeeded Running Transaction Installing : dos2unix-3.1-37.el6.x86_64 1/1 Verifying : dos2unix-3.1-37.el6.x86_64 1/1 Installed: dos2unix.x86_64 0:3.1-37.el6 Complete!
而后执行dos2unix命令将脚本转化为linux环境下的兼容脚本spa
[root@wenhaijin shell]# dos2unix helloworld.sh dos2unix: converting file helloworld.sh to UNIX format ... [root@wenhaijin shell]# ./helloworld.sh Hello World [root@wenhaijin shell]#
4.知识拓展,执行一个shell脚本实现俄罗斯方块的小例子
[root@wenhaijin shell]# chmod 755 Tetris.sh [root@wenhaijin shell]# ./Tetris.sh
这个小游戏的下载地址:http://pan.baidu.com/s/1c1Npu4g.net