shell script 编写和执行

来源:互联网 发布:哈萨克软件下载大全 编辑:程序博客网 时间:2024/06/13 02:55

1. shell script


shell script是针对shell写的脚本。
使用纯文本文件, 将一些shell的语法和命令写在里面,使用户能处理复杂的操作。

2. 编写shell script


先写 hello world。
#!/bin/bash# desc : the first shell script# author : yonggang# date : 2014-01-01echo -e "hello world. \n";exit 0;
第一行“#!/bin/bash” ,声明文件内使用bash语法。当程序执行时,能够自动加载bash的相关环境配置文件。
# 表示注释
exit表示中断程序,并且返回 0 给系统.

3. shell script 执行


直接命令执行:
    需要文件有rx权限。
    当前目录下使用相对路径:  ./hello.sh 
    或者使用绝对路径: /home/work/hello.sh
以bash命令执行:
    sh hello.sh  或 bash hello.sh
    这时只需要r权限。
    /bin/sh 是系统内 /bin/bash 的连接文件,所以使用 sh hello.sh 也可以执行。

4. 使用source执行


source 会让shell在父进程中执行。
#!/bin/bashuser_name="gang"echo -e "User name is : ${user_name}"
执行
[work@www sh]$ sh hello.sh User name is : gang[work@www sh]$ echo $user_name[work@www sh]$ source hello.sh User name is : gang[work@www sh]$ echo $user_name gang[work@www sh]$ 
source会让脚本在父进程中执行。

如果修改~/.bashrc , 在不注销系统情况下想设置生效时,使用 source ~/.bashrc.

5. 默认变量


shell script中的变量可以使用, 命令后面跟参数的形式传递进去。
“sh hello.sh one two”
文件名为$0,  即 hello.sh
$1 为 one
$2  为 two

$# : 参数个数
$@ : 代表“$1” "$2" 等, 用“”包围。
$* : 代表“$1c$2c$3”, c为分隔字符,默认为空格,本例中代表: “$1 $2”
#!/bin/bashecho "The script name  => $0"echo "Parameter number => $#"echo "Whole parameter is => $@"echo "The first is   => $1"echo "The Second is => $2"
运行结果
[work@www sh]$ sh hello.sh one two three fourThe script name  => hello.shParameter number => 4Whole parameter is => one two three fourThe first is   => oneThe Second is => two[work@www sh]$ 

shift可以改变参数变量,将最开始的删掉
#!/bin/bashecho "Parameter number => $#"echo "Whole parameter is => $@"shiftecho "Parameter number => $#"echo "Whole parameter is => $@"shift 2echo "Parameter number => $#"echo "Whole parameter is => $@"
运行
[work@www sh]$ sh hello.sh one two three four five six Parameter number => 6Whole parameter is => one two three four five sixParameter number => 5Whole parameter is => two three four five sixParameter number => 3Whole parameter is => four five six
第一次shift 删掉 one
第二次shift 2  删掉 two three 两个

地址:http://blog.csdn.net/yonggang7/article/details/40478101

0 0