Linux 第三篇 shell

一.shell的基本认识

shell 就是命令解析器,将用户输入的指令转换为相应的机器能够运行的程序。

shell种类: Bourne Shell (sh)

                   Korn Shell (ksh)

                   Bourne Again Shell (bash)

                   C Shell (包括csh and tcsh)

                   TENEXITOPS C Shell (tcsh)

 

二.shell脚本

shell 脚本:是一种包含一系列命令序列的文本文件。当运行这个脚本文件时,文件中包含的命令序列将等到执行。

执行sh文件命令,常用的有两种方式:sh hello.sh  或者 ./shello.sh

以上的执行,都是切换到sh脚本所在目录的执行方式。如果不在sh脚本所在的目录,但是拥有执行权限的话,可以使用指定路径的方式执行。例如:/data/shell/hello.sh

 

shell脚本的编写

语法

shell脚本的第一行必须是如下格式:#! /bin/sh

当编辑好脚本后,如果要执行该脚本,还必须要使其具有可执行属性。

可执行属性的设置命令:chmod +X filename

 

变量

shell编程中,所有变量都是由字符串组成,并不需要预先对变量进行声明。

例:(斜体为注解,实际脚本中不存在,不能写)

#! /bin/sh

# set variable a    //该行为注释:设置一个变量a

a=hello world

# print a

echo A is :       //打印A is :并换行

echo $a           //使用变量a的值:hello world

 

有时候变量的使用很容易与其他文字混淆。

例如:num=2

           echo ”this is the $numnd”

输出为:this is the

原因:因为在解析时,会把numnd 当成变量,而numnd不存在,为空。

如改:num=2

           echo  ”this is the ${num}nd”

输出为:this is the 2nd  

 

默认变量

$# :传入脚本的命令行参数个数

$* :所有命令参数值,在各个参数之间留有空格

$0 :命令本身(shell文件名)

$1 :第一个命令行参数

$2 :第二个命令行参数

……<依次类推>

例:test1.sh

#!/bin/sh

echo ”number of vars:”$#

echo ”number of vars:”$*

echo ”number of vars:”$1

echo ”number of vars:”$2

echo ”number of vars:”$3

echo ”number of vars:”$4

运行test1: ./test1.sh 1 2 3 4

结果会是多少呢?欢迎实验。

 

局部变量

在变量首次被赋值时加上local关键字,可以申明一个局部变量。

例:test2.sh

#!/bin/bash

hello=”var1”

echo $hello

function func1{

    local hello=”var2”

    echo $hello

}

func1

echo $hello

运行test2.

输出结果会是什么呢?欢迎实验。

 

本次的shell,基础认知,就先写到这里。相信当你看到这的时候,对shell已经有了基本的印象。能阅读简单的shell脚本。再见。

发布了5 篇原创文章 · 获赞 11 · 访问量 1259

猜你喜欢

转载自blog.csdn.net/jiachanghui007/article/details/105616317
今日推荐