第一个Shell脚本
打开文本编辑器,新建一个文件,扩展名为sh(sh代表shell),扩展名并不影响脚本执行,见名知意就好,如果你用php写shell 脚本,扩展名就用php好了。
输入一些代码:
- #!/bin/bash
- echo "Hello World !"
运行Shell脚本有两种方法。
作为可执行程序
将上面的代码保存为test.sh,并 cd 到相应目录:chmod +x ./test.sh #使脚本具有执行权限 ./test.sh #执行脚本注意,一定要写成./test.sh,而不是test.sh。运行其它二进制的程序也一样,直接写test.sh,linux系统会去PATH里寻找有没有叫test.sh的,而只有/bin, /sbin, /usr/bin,/usr/sbin等在PATH里,你的当前目录通常不在PATH里,所以写成test.sh是会找不到命令的,要用./test.sh告诉系统说,就在当前目录找。
通过这种方式运行bash脚本,第一行一定要写对,好让系统查找到正确的解释器。
这里的"系统",其实就是shell这个应用程序(想象一下Windows Explorer),但我故意写成系统,是方便理解,既然这个系统就是指shell,那么一个使用/bin/sh作为解释器的脚本是不是可以省去第一行呢?是的。
作为解释器参数
这种运行方式是,直接运行解释器,其参数就是shell脚本的文件名,如:/bin/sh test.sh /bin/php test.php这种方式运行的脚本,不需要在第一行指定解释器信息,写了也没用。
再看一个例子。下面的脚本使用 read 命令从 stdin 获取输入并赋值给 PERSON 变量,最后在 stdout 上输出:
- #!/bin/bash
- # Author : mozhiyan
- # Copyright (c) http://see.xidian.edu.cn/cpp/linux/
- # Script follows here:
- echo "What is your name?"
- read PERSON
- echo "Hello, $PERSON"
chmod +x ./test.sh $./test.sh What is your name? mozhiyan Hello, mozhiyan $
Shell变量:Shell变量的定义、删除变量、只读变量、变量类型
Shell支持自定义变量。定义变量
定义变量时,变量名不加美元符号($),如:
- variableName="value"
- 首个字符必须为字母(a-z,A-Z)。
- 中间不能有空格,可以使用下划线(_)。
- 不能使用标点符号。
- 不能使用bash里的关键字(可用help命令查看保留关键字)。
变量定义举例:
- myUrl="http://see.xidian.edu.cn/cpp/linux/"
- myNum=100
使用变量
使用一个定义过的变量,只要在变量名前面加美元符号($)即可,如:
- your_name="mozhiyan"
- echo $your_name
- echo ${your_name}
- for skill in Ada Coffe Action Java
- do
- echo "I am good at ${skill}Script"
- done
推荐给所有变量加上花括号,这是个好的编程习惯。
重新定义变量
已定义的变量,可以被重新定义,如:
- myUrl="http://see.xidian.edu.cn/cpp/linux/"
- echo ${myUrl}
- myUrl="http://see.xidian.edu.cn/cpp/shell/"
- echo ${myUrl}
只读变量
使用 readonly 命令可以将变量定义为只读变量,只读变量的值不能被改变。下面的例子尝试更改只读变量,结果报错:
- #!/bin/bash
- myUrl="http://see.xidian.edu.cn/cpp/shell/"
- readonly myUrl
- myUrl="http://see.xidian.edu.cn/cpp/danpianji/"
/bin/sh: NAME: This variable is read only.
删除变量
使用 unset 命令可以删除变量。语法:
- unset variable_name
举个例子:
- #!/bin/sh
- myUrl="http://see.xidian.edu.cn/cpp/u/xitong/"
- unset myUrl
- echo $myUrl