如何写一个Shell脚本及其简单语法讲解 您所在的位置:网站首页 linux写一个简单的脚本怎么写的好 如何写一个Shell脚本及其简单语法讲解

如何写一个Shell脚本及其简单语法讲解

2024-07-09 20:30| 来源: 网络整理| 查看: 265

目录

一.Shell文件介绍

二.运行方式

三.举例说明

1.shell文档

2.内容解释

四.如何写一个Shell脚本

1.基本规范

2.使用符号

2.1常用符号

2.2运算符

2.3重定向符

3.使用变量

3.1变量的分类

3.2基本使用方式

3.3交互式定义变量

3.4将命令的结果赋值给变量

4.if语句

5.循环语句

5.1 for循环语句

5.2 while循环语句

5.3 until 循环语句

5.4 break和continue语句

6.数组

7.函数

一.Shell文件介绍

        Linux中.sh文件是脚本文件,一般都是bash脚本。文件后缀名为.sh,其中包含一系列要由操作系统的命令解释器执行的命令。在 Unix 和类 Unix 操作系统中,通常使用 Bourne Shell(sh)或其衍生的 Shell(如 Bash、Zsh)来执行这些脚本,本文叙述的都是Bash Shell脚本。

二.运行方式

        可以使用bash运行,source运行和./ 运行。

bash运行:bash name.sh或者使用sh name.sh,该方法会创建子进程执行shell脚本,不影响当前环境。

source运行:source name.sh,该方式不创建子进程执行,会影响当前环境。

./ 运行:./name.sh。这个运行方式脚本的首行必须要有#!/bin/bash并且需要给脚本添加执行权限chmod +x name.sh,然后进入脚本所在的目录才能直接运行。该方式同bash运行会创建子进程执行shell脚本,不影响当前环境。如图:

        

        

三.举例说明 1.shell文档

        这里以Android12源码中/build/make/banchanHelsp.sh文件为例来进行一些基本的语法讲解:

#!/bin/bash # locate some directories cd "$(dirname $0)" SCRIPT_DIR="${PWD}" cd ../.. TOP="${PWD}" message='usage: banchan ... [|arm|x86|arm64|x86_64] [eng|userdebug|user] banchan selects individual APEX modules to be built by the Android build system. Like "tapas", "banchan" does not request the building of images for a device but instead configures it for an unbundled build of the given modules, suitable for installing on any api-compatible device. The difference from "tapas" is that "banchan" sets the appropriate products etc for building APEX modules rather than apps (APKs). The module names should match apex{} modules in Android.bp files, typically starting with "com.android.". The product argument should be a product name ending in "_", where is one of arm, x86, arm64, x86_64. It can also be just an arch, in which case the standard product for building modules with that architecture is used, i.e. module_. The usage of the other arguments matches that of the rest of the platform build system and can be found by running `m help`' echo "$message" 2.内容解释

(1)在Unix和Linux系统中,bash shell脚本文件的第一行用于指定解释该脚本的程序。通常都是#!/bin/bash,也有第一行为#!/bin/sh的。

        #!:这是一个特殊的标记,它告诉系统接下来的路径是一个解释器的路径,这个解释器是用来执行该脚本的。

        /bin/bash:/bin/bash是bash shell在大多数Linux系统上的默认安装路径。但在有的系统上它可能位于/usr/bin/bash等其他目录,在这种情况下,要把第一行更改为正确的路径。

(2)# locate some directories是注释,一般sh文件没有多行注释,通常使用单行注释,即在语句前加#,语句后添加注释则是空格加上#来撰写单行注释,如果想使用多行注释可以使用以下技巧:

A. 使用:命令,:是一个空命令,表示啥也不做,虽然什么也不会做,但是在:后面的这些行也会被解析,如果这些内容没有实际的命令或者语法上的错误,对sh脚本来说不会产生任何效果。

:'这是一个多行注释

请注意,这不是真正的多行注释

这只是一个不执行任何操作的命令'

B.使用:



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有