【Linux】shell编程(一) 变量

什么是shell编程

简单的命令可以在命令行中直接输入,但是复杂的命令需要写在脚本里。例如一个简单的shell脚本:

#!/bin/bash

#输出一行
echo "Hello World!"

#开始的行是注释行,空行会被忽略。

如何运行shell脚本

  • 方式一:直接输入脚本的相对路径或绝对路径

    ./run.sh
    • 需要给shell脚本添加可执行权限,否则会报错:Permission denied
  • 方式二:sh+脚本的相对路径或绝对路径

    sh ./run.sh
    • 不需要添加可执行权限

第一行 #!/bin/bash

第一行叫什么?

WHAT IS THIS LINE CALLED?

This first line (#!/bin/bash or #!/bin/sh) has a name. It is known as ‘she-bang‘(shabang). This derives from the concatenation of the tokens sharp (#) and bang (!). It is also called as sh-bang, hashbang, poundbang or hash-pling. In computing, a she-bang is the character sequence consisting of the characters number sign and exclamation mark (#!) at the beginning of a script.

shabang,由sharp(#)和bang(!)组合而来,必须位于一个脚本的第一行

为什么要加这个,有什么用?

In Unix-like Operating Systems when a script starting with a she-bang(#!) is executed as a program, the program loader parses the rest of the script’s initial line as a interpreter-directive. Thus the specified interpreter program is run instead, passing to it as an argument the path that was used initially through the script.

In simple words, the she-bang at the head of the script tells the system that this file is a set of commands to be fed to the command interpreter indicated. Unix-like operating systems has variety of shells and each of script header lines call a different command interpreter.

如果shell看到第一行是shabang,shell就知道这个文件是一个shell脚本,并按照shabang的指引到/bin/bash找到指定的shell解释器,然后把文件中的命令传给shell。

解释器可以是bash,也可以是csh等等。

SOME she-bang EXAMPLES

*#!/bin/sh :Executes the script using the Bourne shell or a compatible shell, with path /bin/sh*

*#!/bin/bash :Executes the script using the Bash shell.*

*#!/bin/csh -f :Executes the script using C shell or a compatible shell.*

*#!/usr/bin/perl -T :Executes the script using perl with the option of taint checks*

*#!/usr/bin/env python :Executes the script using python by looking up the path to the python interpreter automatically from the environment variables*

shell的变量

变量的赋值和使用

#!/bin/bash

#将一个字符串赋给变量A
LOG="monday"
echo "The value of logfile is:" #美元符号用于变量替换
echo $LOG

运行结果:

$ sh ./variable.sh
The value of logfile is:
monday
  • 变量的赋值:

    • 变量赋值时,等号两边都不能打空格
    • 变量名可以由字母、数字和下划线组成,但是不能以数字开头
    • 变量名称一般为大写(代码规范,不是语法要求)
  • 变量的使用:

    • 当需要使用变量时,要用$对变量进行替换。BASH中,美元符号"$"用于对一个变量进行解析,shell在碰到$引导的变量时,会自动将其换成这个变量的值。
  • 变量作用范围

    • 变量只在其所在脚本有效。

    • source可以强行让一个脚本影响其父环境

      • $ source variable.sh
        The value of logfile is:
        monday
        $ echo $LOG
        monday
    • 与之相反,export可以让脚本影响其子shell环境

      • $ export count=5		 ##输出变量count
        $ bash ##启动子shell
        $ echo $count
        5
        $ exit ##回到先前的shell中
        exit
    • 使用unset可以注销变量

      • unset log

变量替换

  • $用于解析变量,如果要输出这个符号,需要使用转义字符'\'

    • $ LOG='Monday'
      $ echo
  • shell提供了花括号"{}"来限定一个变量的开始和结束。当需要紧跟变量输出字母后缀时,必须使用这个功能

    • $ WORD='big'
      $ echo "This apple is ${WORD}ger"
      This apple is bigger

位置变量

可以向shell脚本传命令行参数,shell脚本中使用以数字命名的变量来存放这些参数,称为位置变量。

  • 简单地说,第一个位置变量存放在$1,第二个存放在$2,以此类推。当变量数量超过10个时,需要加花括号把数字括起来。例如${10},${23}等。

  • $0用于存放脚本自己的名字。

!#/bin/bash

echo "\$0 = *$0*"
echo "\$1 = *$1*"
echo "\$2 = *$2*"
echo "\$3 = *$3*"

运行结果:

$ sh ./diaplay_para.sh first second
$0 = *display_para.sh*
$1 = *firsh*
$2 = *second*
$3 = ** ##不存在第三个变量,所以为空

除了以数字命名的变量外,shell还提供了另外三个位置变量:

  • $*:包含参数列表
  • $@:包含参数列表,同上
  • $#:包含参数的个数
#!/bin/bash

#显示有多少个参数需要列出
echo "The number of parameter is $#" for para in $@
do
echo $para ##也可以写成 echo "$para"
done

运行结果:

$ sh ./list_para.sh first second
The number of parameter is 2
first
second

BASH引号规则

shell脚本中可以使用的引号有以下三种:

  • 双引号:阻止Shell对大多数特殊字符(例如#)进行解释。但“$”、"`"和"""仍然保持其特殊含义
  • 单引号:阻止Shell对所有字符进行解释
  • 倒引号:"``",这个符号通常位于键盘Esc键的下方。当用倒引号括起一个Shell命令时,命令会被执行,并将执行后的结果作为表达式的值。
#!/bin/bash

LOG=Saturday

echo "Today is $LOG"
echo 'Today is $LOG' echo "Today is `date`"
echo 'Today is `date`'

运行结果:

Today is Saturday
Today is $LOG Today is Thu Jun 8 17:37:43 CST 2023
Today is `date`

小结

  • 运行Shell脚本:sh+脚本的相对路径或绝对路径。
  • 第一行的"#!/bin/bash"是shabang(sharp bang),表明Shell解释器的路径。有Shabang的文件运行时会被自动识别成Shell脚本。
  • 变量赋值时,等号两边不能有空格。
  • $符号后面的变量会被自动替换成变量的值。
  • 数字命名的变量表示传入的位置变量,如$1, ${12}。"$@"和"$*"表示位置变量列表,"$#"表示位置变量的数量。
  • 双引号阻止大多数字符解析,单引号阻止所有字符解析,倒引号执行命令并作为表达式的值。

【Linux】shell编程(一) 变量的更多相关文章

  1. Linux Shell编程、变量、控制语句

    为什么要学习Shell编程 1)Linux运维工程师在进行服务器集群管理时,需要编写Shell程序来进行服务器管理. 2)对于JavaEE和Python程序员来说,工作的需要,你的老大会要求你编写一些 ...

  2. Linux —— Shell编程之变量赋值和引用

    Linux的shell编程是一种非常成熟的编程语言,它支持各种类型的变量.有三种主要的变量类型:环境变量.内部变量和用户变量. 环境变量(environment variable)是系统环境的一部分, ...

  3. linux shell编程之变量和bash配置文件(第一篇)

    编程语言有两类 强类型:如C语言.数据具有其特定的类型,先声明定义后才能使用.数据运算时必须符合类型要求(如不能把字符串类型数据直接与整型数据做算数运算) 弱类型:如shell.数据默认为字符型,不用 ...

  4. Linux学习——shell编程之变量

    shell编程之变量:Linux shell编程基础中的变量. 包括Bash变量的分类和各变量的详细使用,如:用户自定义变量.环境变量.语系变量.位置参数变量和预定义变量. 1:什么是Bash变量? ...

  5. linux —— shell 编程(文本处理)

    导读 本文为博文linux —— shell 编程(整体框架与基础笔记)的第4小点的拓展.(本文所有语句的测试均在 Ubuntu 16.04 LTS 上进行) 目录 基本文本处理 流编辑器sed aw ...

  6. linux —— shell 编程(编程语法)

    导读 本文为博文linux —— shell 编程(整体框架与基础笔记)的第4小点的拓展.(本文所有语句的测试均在 Ubuntu 16.04 LTS 上进行) 目录 再识变量 函数 条件语句 循环语句 ...

  7. linux shell编程总结

    linux shell编程总结 本周学习了unix/linux shell编程,参考的是<LINUX与UNIX Shell 编程指南>,David Tansley著:徐焱,张春萌等译,由机 ...

  8. Linux Shell编程参考大全

    本文记录Linux Shell编程中常用基本知识,方便快速入门以及查询使用. 本文主要分为以下几个部分: 一.Shell中的变量 任何编程语言中,有关变量的定义,作用范围,赋值等都是最最基础的知识. ...

  9. Linux Shell编程中的几个特殊符号命令 & 、&& 、 ||

    https://blog.csdn.net/hack8/article/details/39672145 Linux Shell编程中的几个特殊符号命令 & .&& . || ...

  10. linux shell 编程参考

    #!/bin/bash my_fun() { echo "$#" } echo 'the number of parameter in "$@" is '$(m ...

随机推荐

  1. git 从本地仓库提交至远程仓库 报错:error: failed to push some refs to "xxx"

    **原因**:远程库里面有个文件,但是本地没有这个文件,比如: README.md,完全提交上去会覆盖之前的文件,所以git会提示报错警告! **解决方案**:如果只有 README.md文件,可以使 ...

  2. 记一次 .NET 某医疗住院系统 崩溃分析

    一:背景 1. 讲故事 最近收到了两起程序崩溃的dump,查了下都是经典的 double free 造成的,蛮有意思,这里就抽一篇出来分享一下经验供后面的学习者避坑吧. 二:WinDbg 分析 1. ...

  3. StringBuilder 导致堆内存溢出

    StringBuilder 导致堆内存溢出 原始问题描述: Exception in thread "main" java.lang.OutOfMemoryError: Java ...

  4. $\mathcal{Mathicの代码风格}$

    概述 \(#include\) 语句必须置于整个程序的开头. 不应 using namespace foo; 若有必要可以 using foo::bar; 单行字符数必须不超过\(80\). 预编译 ...

  5. 自己定义jquery插件轮播图

    轮播图-html <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...

  6. Hive 和 Spark 分区策略剖析

    作者:vivo 互联网搜索团队- Deng Jie 随着技术的不断的发展,大数据领域对于海量数据的存储和处理的技术框架越来越多.在离线数据处理生态系统最具代表性的分布式处理引擎当属Hive和Spark ...

  7. Vim基本使用方法来啦

    一.Vim是什么 Vim是一个高度可配置的文本编辑器,用于创建和更改任何类型的文本非常高效.与大多数UNIX系统和Apple OS X一起,它被包含为"vi".Vim是稳定的,并且 ...

  8. flask+gunicorn+nginx部署pytorch/python应用

    1. 基于flask实现python服务Flask是一个使用 Python 编写的轻量级 Web 应用框架.其 WSGI 工具箱采用 Werkzeug ,模板引擎则使用 Jinja2 .Flask使用 ...

  9. python之PySimpleGUI(二)属性

    属性 Size• Key 相当于句柄/ID• Font• Pad• Colors• Enable Events• Visibility• Tooltip• Metadata• Right click ...

  10. Go语言核心知识回顾(接口、Context、协程)

    温故而知新 接口 接口是一种共享边界,计算机系统的各个独立组件可以在这个共享边界上交换信息,在面向对象的编程语言,接口指的是相互独立的两个对象之间的交流方式,接口有如下好处: 隐藏细节: 对对象进行必 ...