【Linux编程Shell自动化脚本】01 Shell 变量、条件语句及常用概念操作等详解

一、简介

Shell是操作系统的最外层,Shell可以合并编程语言以控制进程和文件,以及启动和控制其它程序。shell 通过提示您输入,向操作系统解释该输入,然后处理来自操作系统的任何结果输出来管理您与操作系统之间的交互。简单来说Shell就是一个用户跟操作系统之间的一个命令解释器。

Shell是用户与Linux操作系统之间沟通的桥梁。用户可以输入命令执行,又可以利用 Shell脚本编程去运行。

在这里插入图片描述
Linux Shell种类非常多,常见的有:Bourne Shell(/usr/bin/sh或/bin/sh)、Bourne Again Shell(/bin/bash)、C Shell(/usr/bin/csh)、K Shell(/usr/bin/ksh)、Shell for Root(/sbin/sh)等。不同的Shell语言的语法有所不同,所以不能交换使用。

最常用的shell是Bash,也就是Bourne Again Shell,由于易用和免费,Bash在日常工作中被广泛使用,也是大多数Linux系统默认的Shell。

一个shell脚本示例:

#!/bin/bash
#Filename: first_shell.sh
#该shell脚本实现的功能
#by authors xiaoming 2023(作者/时间)

echo "Hello world!"

首先执行shell脚本需要执行权限,赋予执行权限:chmod o+x first_shell.sh 然后./first_shell.sh执行即可;
也可以直接使用命令执行: /bin/sh first_shell.sh,显示效果一样。

#! 告诉系统其后路径所指定的程序即是解释此脚本文件的 Shell 程序。

二、变量详解

Shell编程语言是非类型的解释型语言,不像C++/JAVA语言编程时需要事先声明变量,SHELL给一个变量赋值,实际上就是定义了变量,在Linux支持的所有shell中,都可以用赋值符号(=)为变量赋值。

SHELL变量可分为两类:局部变量和环境变量。局部变量只在创建它们的shell脚本中使用。而环境变量则可以在创建它们的shell及其派生出来的任意子进程中使用。有些变量是用户创建的,其他的则是专用shell变量。

注意,shell变量赋值时,变量名和等号之间不能有空格。同时,变量名的命名须遵循如下规则:

  • 命名只能使用英文字母,数字和下划线,首个字符不能以数字开头。
  • 中间不能有空格,可以使用下划线 _。
  • 不能使用标点符号。
  • 不能使用bash里的关键字(可用help命令查看保留关键字)。

1. 系统变量

SHELL常见的系统变量解析:

  • $0 当前程序的名称
  • $n 当前程序的第n个参数,n=1,2,…9
  • $* 当前程序的所有参数(不包括程序本身)
  • $# 当前程序的参数个数(不包括程序本身)
  • $? 命令或程序执行完后的状态,一般返回0表示执行成功。
  • $UID 当前用户的ID
  • $PWD 当前所在的目录

一个示例:

#!/bin/bash
#auto print variables
#by xiaoming 2023
echo -e '\033[32m-----------------------------\033[0m'
echo "This is $0 param !"
echo "This \$1 is $1 param !"
echo "This \$2 is $2 param !"
echo -e '\033[32m-----------------------------\033[0m'
echo "This \$* is $* param !"
echo "This \$# is $# param !"
echo "This \$? is $? param !"
echo

echo -e:enable interpretation of backslash escapes

使用 ANSI 转义码更改输出颜色

ANSI 转义序列是一个允许终端接收信息的标准,不仅是关于字体样式和颜色,还有光标的位置和许多其他终端选项。为了对这些信息进行编码,一个不同的字符序列被直接嵌入到它接收到的文本中。终端不是将这些序列解释为要打印的字符,而是解释为命令。
ANSI 转义序列总是以转义字符开头,可以用以下三种方式之一编写:

\e
\033 
\x1B

如果我们看一下 ASCII 表,我们可以看到这三个符号都对应于第 27个ASCII 字符 ESC(转义)。第一个是它的文本符号,第二个是它的八进制数,第三个是它的十六进制数。

在大多数情况下,转义字符后跟一个左括号“[”。这两个字节一起构成了 CSI,即“控制序列引入器”。

这是完整的 ANSI 控制结构:

"\e" + "[" + <numbers separated with ";" (optional)> + <letter>

我们可以将这样的控制序列视为函数调用,其中末尾的字母是函数的名称,中间的可选数字是参数。

\e[1;42m为例,可以解释为:

\e[    # function call
1;42   # function parameters (1, 42) 
m      # function name

ANSI 代码不仅限于颜色,还可以用于样式。代码0..9代表文本样式,而代码30...37代表颜色:
在这里插入图片描述
同样,您可以使用代码更改这些文本的背景颜色40..47
在这里插入图片描述
如果我们用分号分隔每个属性,我们可以在一个 ANSI 转义序列中完成所有这些:

echo -e "\e[0;1;2;3;4;5;6;7;9mHello\e[0m"

注意:更改给定字符串的背景归结为与更改字体颜色时相同的规则 - 代码本身会更改显示的颜色行为

重置文本格式的命令为:

Color_Off='\033[0m'       # Text Reset, equals to '\033[m'

三、If条件语句

格式:

if condition1
then
    command1
elif condition2 
then 
    command2
else
    commandN
fi

实用的命令:

  • mkdir -p, --parents
    no error if existing, make parent directories as needed, with their file modes unaffected by any -m option.
    借助 mkdir -p 命令,可以创建目录的子目录。如果不存在,它将首先创建父目录。但如果它已经存在,那么它不会打印错误消息,而是会进一步创建子目录。
  • wget -c, --continue
    继续获取部分下载的文件,当想要完成由先前的 wget 或另一个程序启动的下载时,这很有用。例如:
    wget -c ftp://sunsite.doc.ic.ac.uk/ls-lR.Z
    
    如果当前目录下有名为ls-lR.Z的文件,wget会认为它是远程文件的第一部分,并会要求服务器从等于本地文件长度的偏移量开始继续检索.

1. ()、(())、[]、[[]]、let和test的区别

(1)bash中的Compound Commands
  • ((expression))
    The expression is evaluated according to the rules described below under ARITHMETIC EVALUATION. If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1. This is exactly equivalent to let “expression”.

  • [[ expression ]]
    Return a status of 0 or 1 depending on the evaluation of the conditional expression expression. Expressions are composed of the primaries described below under CONDITIONAL EXPRESSIONS. Word splitting and pathname expansion are not performed on the words between the [[ and ]]; tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal are performed.
    Expressions may be combined using the following operators, listed in decreasing order of precedence:

    • ( expression )
      Returns the value of expression. This may be used to override the normal precedence of operators.
    • ! expression
      True if expression is false.
    • expression1 && expression2
      True if both expression1 and expression2 are true.
    • expression1 || expression2
      True if either expression1 or expression2 is true.
(2)Shell Builtin Commands
  • let arg [arg …]
    Each arg is an arithmetic expression to be evaluated. If the last arg evaluates to 0, let returns 1; 0 is returned otherwise.
  • test expr等价于[ expr ]
    Return a status of 0 or 1 depending on the evaluation of the conditional expression expr. Each operator and operand must be a separate argument. Expressions are composed of the primaries described above under CONDITIONAL EXPRESSIONS. test does not accept any options, nor does it accept and ignore an argument of – as signifying the end of options.
    Expressions may be combined using the following operators, listed in decreasing order of precedence. The evaluation depends on the number of arguments; see below.
    • ! expr
      True if expr is false.
    • ( expr )
      Returns the value of expr. This may be used to override the normal precedence of operators.
    • expr1 -a expr2
      True if both expr1 and expr2 are true.
    • expr1 -o expr2
      True if either expr1 or expr2 is true.

test and [ evaluate conditional expressions using a set of rules based
on the number of arguments.

  • 0 arguments
    The expression is false.
  • 1 argument
    The expression is true if and only if the argument is not null.
  • 2 arguments
    If the first argument is !, the expression is true if and only if the second argument is null. If the first argument is one of the unary conditional operators listed above under CONDITIONAL EXPRESSIONS, the expression is true if the unary test is true. If the first argument is not a valid unary conditional operator, the expression is false.
  • 3 arguments
    If the second argument is one of the binary conditional operators listed above under CONDITIONAL EXPRESSIONS, the result of the expression is the result of the binary test using the first and third arguments as operands. The -a and -o operators are considered binary operators when there are three arguments. If the first argument is !, the value is the negation of the two-argument test using the second and third arguments. If the first argument is exactly ( and the third argument is exactly ), the result is the one-argument test of the second argument. Otherwise, the expression is false.
  • 4 arguments
    If the first argument is !, the result is the negation of the three-argument expression composed of the remaining arguments. Otherwise, the expression is parsed and evaluated according to precedence using the rules listed above.
  • 5 or more arguments
    The expression is parsed and evaluated according to precedence using the rules listed above.
(3)Arithmetic Evaluation

The shell allows arithmetic expressions to be evaluated, under certain circumstances . Evaluation is done in fixed-width integers with no check for overflow, though division by 0 is trapped and flagged as an error. The operators and their precedence, associativity, and values are the same as in the C language.

  • id++ id–
    variable post-increment and post-decrement
  • ++id --id
    variable pre-increment and pre-decrement
(4)Conditional Expressions

Conditional expressions are used by the [[ compound command and the test and [ builtin commands to test file attributes and perform string and arithmetic comparisons. Expressions are formed from the following unary or binary primaries.

(5)分类总结

Compound Commands

  • ((expression))
  • [[ expression ]]

Shell Builtin Commands

  • let arg [arg …]
  • test expr
  • [ expr ]

Arithmetic Evaluation

  • let arg [arg …]
  • ((expression))

Conditional Expressions

  • [[ expression ]]
  • test expr
  • [ expr ]

在碰到[]和[[]]分不清的场景时,可以想象[]是和test命令等价的,其中没有关系运算符的操作,比如>=,<=这些

2. 常见的逻辑运算符

  • -f file
    True if file exists and is a regular file.
  • -d file
    True if file exists and is a directory.
  • -z string
    True if the length of string is zero.
  • -n string
    True if the length of string is non-zero.
  • arg1 OP arg2
    OP is one of -eq, -ne, -lt, -le, -gt, or -ge. These arithmetic binary operators return true if arg1 is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to arg2, respectively. Arg1 and arg2 may be positive or negative integers.
  • string1 == string2 或 string1 = string2
    True if the strings are equal. = should be used with the test command for POSIX conformance.
  • string1 != string2
    True if the strings are not equal.
  • string1 < string2
    True if string1 sorts before string2 lexicographically.
  • string1 > string2
    True if string1 sorts after string2 lexicographically.

When used with [[, The < and > operators sort lexicographically using the current locale.

test或[ expr ]独有的运算符

  • -a 双方都成立(and) 逻辑表达式 –a 逻辑表达式
  • -o 单方成立(or) 逻辑表达式 –o 逻辑表达式

3. Shell中的分号

When the shell sees a semicolon (;) on a command line, it’s treated as a command separator – basically like pressing the ENTER key to execute a command.

(1)单行语句一般要用到分号来区分代码块
if [ "$PS1" ]; then echo test is ok; fi
test is ok

该脚本或命令行中,需要两个分号才为正确的语句,第一个分号是then前的分号,用于标识条件块结束,第二个分号在fi前,用于标识then块结束,如果缺少这两个分号,则程序执行错误。

注意:语句结尾不要分号。

(2)该代码若写作多行,用换行符来区分代码块,则无需用到分号
if [ "$PS1" ]
> then echo test is ok
> elif [ "$PS2" ] 
> then echo here
> fi
test is ok

从这个例子可看出if判断语句分if块,then块,elif块和fi结束标识

四、其他常用操作

1. Shell中的引号""、''和``的区别

在 Shell 中引号分为三种:双引号、单引号和反引号。

(1)双引号 “”

由双引号括起来的字符,除$、反引号和反斜杠(\)仍然保留其特殊功能外,其余字符通常作为普通字符对待。示例:

#!/bin/bash

echo "My current directory is `pwd`"
echo "My home the directory is $HOME \n"
(2)单引号 ‘’

由单引号括起来的所有字符或字符串都作为普通字符出现。如果将上例中的双引号改为单引号,则 pwd 和 $HOME 就会作为普通字符输出,而失去原有的特殊意义。总结的说就是,被单引号括起来的字符,是什么就输出什么。

(3)反引号 ``

`…`是命令替换的遗留语法,只有最古老的非 POSIX 兼容的Bourne shell才需要。

Shell中的命令替换

  • $(command)
  • `command`

二者的区别:

  • ``内部的反斜杠(\)以一种不明显的方式处理
$ echo "`echo \\a`" "$(echo \\a)"
a \a
$ echo "`echo \\\\a`" "$(echo \\\\a)"
\a \\a
# Note that this is true for *single quotes* too!
$ foo=`echo '\\'`; bar=$(echo '\\'); echo "foo is $foo, bar is $bar"
foo is \, bar is \\
  • 在 $() 中嵌套引号要方便得多
echo "x is $(sed ... <<<"$y")"

在这个例子中,$y 周围的引号被视为一对,因为它们在$()内部。乍一看,这是令人困惑的,因为大多数C程序员会期望x前面的引号和$y前面的引号被视为一对;但这在shell中是不正确的。另一方面,

echo "x is `sed ... <<<\"$y\"`"

需要在内部引号周围加上反斜杠以便于移植。Bourne和Korn shell需要这些反斜杠,而Bash和dash则不需要。

  • $(command) 使嵌套命令替换更容易。比较:
x=$(grep -F "$(dirname "$path")" file)
x=`grep -F "\`dirname \"$path\"\`" file`

使用``加了两层后就越来越难看了。而$()强制为引号创建一个全新的上下文,因此命令替换中的所有内容都受到保护,并且可以被视为独立的,而不需要特别关注引号和转义。

2. date命令用法

命令格式:

date [OPTION]... [+FORMAT]
(1)-d选项(等同于–date=STRING)

显示由用户字符串描述的时间,而不是now。

date -d "+5 days"
date -d "+7 weeks +2 days"
date -d "last Wednesday 2 pm"

--date=STRING 是一个基本自由格式的人类可读日期字符串,如"Sun, 29 Feb 2004 16:21:42 -0800"或"2004-02-29 16:21:42”甚至是“next Thursday”。日期字符串可能包含显示日历日期、时间、时区、星期日期、相对时间、相对日期和数字。空字符串表示一天的开始。

(2)-s选项(等同于–set=STRING)

根据字符串设置系统时间。

(3)格式化输出选项

要格式化date命令的输出,可以使用前面带有符号的控制字符+。格式控件以%符号开头,并替换为它们的当前值。

示例:

date +"Year: %Y, Month: %m, Day: %d"

常用格式字符:

  • %D – Display date as mm/dd/yy
  • %Y – Year (e.g., 2020)
  • %m – Month (01-12)
  • %B – Long month name (e.g., November)
  • %b – Short month name (e.g., Nov)
  • %d – Day of month (e.g., 01)
  • %j – Day of year (001-366)
  • %u – Day of week (1-7)
  • %A – Full weekday name (e.g., Friday)
  • %a – Short weekday name (e.g., Fri)
  • %H – Hour (00-23)
  • %I – Hour (01-12)
  • %M – Minute (00-59)
  • %S – Second (00-60)

要查看所有格式选项,请在终端中运行 date --help 或 man date

3. 定时任务 crontab -e

crontab命令是cron table的简写,它是cron的配置文件,也可以叫它作业列表。

cron是计划任务,可以在约定的时间执行既定的任务

如果用户名出现在/usr/lib/cron/cron.allow文件中,则可以执行crontab。如果该文件不存在,则如果用户名没有出现在/usr/lib/cron/cron.deny.文件中,可以使用使用Crontab。
如果只存在cron.deny且为空,则所有用户都可以使用crontab。如果两个文件都不存在,则只有root用户可以使用crontab。allow/deny文件每行包含一个用户名。

相关文件:

  • /etc/crontab——main system crontab file.
  • /var/spool/cron/——a directory for storing crontabs defined by users.
  • /etc/cron.d/——a directory for storing system crontabs.

cron.d和/etc/crontab中的任务是系统作业,通常用于不止一个用户,因此额外的用户名是有必要的。第一行的MAILTO是可选的。
示例:

#login as root
#create job with preferred editor (e.g. vim)
MAILTO=root
* * * * * root touch /tmp/file

命令格式:

crontab [-u username]    //省略用户表表示操作当前用户的crontab
    -e      (编辑工作表)
    -l      (列出工作表里的命令)
    -r      (删除工作作)

cron条目语法:
crontab文件有五个字段用于指定时间,后面跟着要在该间隔内运行的命令。

fieldallowed values
minute0-59
hour0-23
day of month1-31
month1-12 (or names, see below)
day of week0-7 (0 or 7 is Sunday, or use names)

在这里插入图片描述
上面value字段中的*表示该列的大括号中的所有合法值。

value列可以包含一个*或者是由逗号分隔的元素列表。一个元素要么是上面所示范围内的一个数字,要么是由连字符`-``分隔的两个数字(表示包含范围)。

注意:

  • 并非所有操作系统都支持/2表示每2分钟或/10表示每10分钟这样的重复模式。如果尝试使用它,crontab可能不支持。
  • 指定day可以通过两个字段: day of month和day of week。如果它们都在一个条目中指定,则它们是累积的,这意味着满足两个时间都将被执行。

一些示例:

  • 每1分钟执行一次myCommand
* * * * * myCommand
  • 每小时的第3和第15分钟执行
3,15 * * * * myCommand
  • 在上午8点到11点的第3和第15分钟执行
3,15 8-11 * * * myCommand
  • 每隔两天的上午8点到11点的第3和第15分钟执行
3,15 8-11 */2  *  * myCommand
  • 晚上11点到早上7点之间,每隔一小时执行
0 23-7/1 * * * myCommand

4. tar命令 -jxvf -xzvf

常用选项

  • -c, --create 创建一个新的存档
  • -j, --bzip2 通过 bzip2 过滤存档
  • -z , --gzip 通过 gzip 过滤存档
  • -x, --extract, --get 从存档中提取文件
  • -v, --verbose 详细列出已处理的文件
  • -f, --file=ARCHIVE 使用存档文件或设备 ARCHIVE
  • -C , --directory=DIR 更改目录 DIR
  • -g, --listed-incremental=FILE 处理新的GNU格式增量备份

5. ./configure && make && make install(Unix C程序配置、制作和安装)

此过程分为三个不同的步骤:

  1. 配置软件
    configure脚本负责准备好在特定系统上构建软件。它确保其余构建和安装过程的所有依赖项都可用,并找出使用这些依赖项需要知道的任何信息。
    Unix 程序通常是用 C 编写的,所以我们通常需要一个 C 编译器来构建它们。在这些情况下,configure脚本将确定系统确实有一个 C 编译器,并找出它的名称和位置。

  2. 构建软件
    一旦configure完成它的工作,我们就可以调用make来构建软件。这将运行 Makefile 中定义的一系列任务,以从其源代码构建程序。
    下载的 tarball 通常不包含完成的Makefile。相反,它带有一个名为Makefile.in的模板,configure 脚本会生成一个特定于系统定制Makefile文件。

  3. 安装软件
    现在软件已构建并准备好运行,可以将文件复制到它们的最终目的地。make install命令会将构建的程序及其库和文档复制到正确的位置。
    这通常意味着程序的二进制文件将被复制到PATH目录中,程序的手册页将被复制到MANPATH目录中,并且它所依赖的任何其他文件都将安全地存储在适当的位置。
    由于安装步骤也在Makefile中定义,因此安装软件的位置可能会根据传递给configure脚本的选项或configure脚本发现的与系统有关的内容而改变。

总结:

  • You run configure (you usually have to type ./configure as most people don’t have the current directory in their search path). This builds a new Makefile.
  • Type make This builds the program. That is, make would be executed, it would look for the first target in Makefile and do what the instructions said. The expected end result would be to build an executable program.
  • Now, as root, type make install. This again invokes make, make finds the target install in Makefile and files the directions to install the program.

Linux中使用源码安装软件时,有的会提供configure脚本,使用./configure指令来生成makefile,有的则是提供cmakelist.txt,通过cmake指令来生成makefile。
./configure是一种叫autoconf的构建工具自动生成的构建文件,它以shell script的形式存储,在cmake之前是c/c++的主流构建工具。近年来很多项目有从autoconf转向cmake的趋势。autoconf和cmake的共同点是会生成makefile,然后从makefile执行真正的编译构建过程。使用哪一个取决于文件夹下面的INSTALL文件,此文件会说明你应该采用哪一个构建工具

6. chkconfig命令

(1)命令说明
  • –add name:增加所指定的系统服务,让chkconfig指令得以管理它,并同时在系统启动的叙述文件内增加相关数据;
  • –del name:删除所指定的系统服务,不再由chkconfig指令管理,并同时在系统启动的叙述文件内删除相关数据;
  • –list [name]:列出chkconfig知道的所有服务,以及它们在每个运行级别中是停止还是启动。如果指定name,则仅显示有关服务名称的信息。
  • –level <等级代号> name:指定读系统服务要在哪一个执行等级中开启或关毕。
  • –level <等级代号> name <on|off|reset|resetpriorities>
    • 如果在服务名称后指定了onoffresetresetpriorities之一, chkconfig会更改指定服务的启动信息。onoff标志分别导致服务在正在更改的运行级别中启动或停止。reset标志将服务所有运行级别的开/关状态重置为相关初始化脚本中指定的任何内容,而resetpriorities标志将服务的启动/停止优先级重置为初始化脚本中指定的任何内容。
    • 默认情况下,onoff选项仅影响运行级别 2、3、4 和 5,而resetresetpriorities影响所有运行级别。–level选项可用于指定受影响的运行级别。

对各个运行级的解释
0:关机
1:单用户模式
2:无网络支持的多用户模式
3:有网络支持的多用户模式
4:保留,未使用
5:有网络支持有X-Window支持的多用户模式
6:重新引导系统,即重启

(2)systemctl与service、chkconfig命令对比
任务旧指令新指令
使某服务自动启动chkconfig –level 3 httpd onsystemctl enable httpd.service
使某服务不自动启动chkconfig –level 3 httpd offsystemctl disable httpd.service
检查服务状态service httpd statussystemctl status httpd.service (服务详细信息)/ systemctl is-active httpd.service (仅显示是否 Active)
加入自定义服务chkconfig –add testsystemctl load test.service
删除服务chkconfig –del xxx停掉应用,删除相应的配置文件
显示所有已启动的服务chkconfig –listsystemctl list-units –type=service
启动某服务service httpd startsystemctl start httpd.service
停止某服务service httpd stopsystemctl stop httpd.service
重启某服务service httpd restartsystemctl restart httpd.service

7. ifconfig命令

ifconfig命令用于显示或设置网络设备。

命令格式:

ifconfig [-a] [interface]

如果没有指定参数,ifconfig将显示当前活动接口的状态。如果给出了单个接口参数,它只显示给定接口的状态;如果给出一个-a参数,它将显示所有接口的状态,甚至是那些down的接口。否则,配置接口。

8. cut命令

cut命令用于从文件的每行中截取部分

命令格式:

cut OPTION... [FILE]...

参数选项:

  • -b, --bytes=LIST 选择指定字节
  • -c, --characters=LIST 选择指定字符
  • -d, --delimiter=DELIM 使用DELIM代替默认的TAB作为域分隔符
  • -f, --fields=LIST 只选择这些字段,还要打印任何不包含分隔符的行,除非指定了-s选项
  • -s, --only-delimited 不打印不包含分隔符的行

仅使用-b、-c或-f中的一个时,LIST可以是由一个范围或多个用逗号分隔的范围组成,每个范围可以是如下格式:

  • N N’th byte, character or field, counted from 1
  • N- from N’th byte, character or field, to end of line
  • N-M from N’th to M’th (included) byte, character or field
  • -M from first to M’th (included) byte, character or field

示例:
打印出 /etc/passwd 文件每一行的第一个字段

cut -d':' -f1 /etc/passwd

8. cat << EOF 的用法

(1)cat命令

cat(英文全拼:concatenate)命令用于连接文件并打印到标准输出设备上。

如果未指定文件名或者指定连字符-作为参数,则从标准输入读取内容,cat 命令复制标准输入到标准输出。

通过cat配合重定向能够生成文件并追加操作,在它之前先熟悉几个特殊符号

<:输入重定向

>:输出重定向

>>:输出重定向,进行追加,不会覆盖之前内容

<<:标准输入来自命令行的一对分隔号的中间内容

cat 命令重定向文件的内容

默认情况下,cat 命令将内容写入标准输出。但你可以使用标准输出的重定向操作符 > 或者 >> 将标准输出重定向到文件,而不是终端的屏幕。

当 cat 命令与重定向操作符一起使用时,你会发现 cat 命令也可实现cp命令的复制文件操作。

例如命令 cat file1.txt > file2.txt 将 file1.txt 的内容写入标准输出然后使用重定向操作符 > 重定向到 file2.txt。

如果 file2.txt 文件不存在,cat 命令将创建该文件。否则,它将被覆盖file2.txt。

如果不想被覆盖,还可以使用另一个标准输出重定向操作符>>,>>操作符可追加任何内容到指定设备或者文件。

cat file1.txt > file2.txt
cat file1.txt >> file2.txt

cat 命令创建文件

运行命令 cat > file1.txt,当用户的完成内容的出入后,可按快捷键 CRTL+D 保存文件。如果用户不知道如何保存内容时,可在运行 cat 之前告诉用户保存的快捷键是 CRTL+D。

cat > file1.txt
(2)EOF的用法

EOF是(END Of File)的缩写,表示自定义终止符。既然自定义,那么EOF就不是固定的,可以随意设置别名,在linux按ctrl-d 就代表EOF。

cat <<eof 使用“here-document”。here-document 是 Linux 中的代码块。它将输入/输出重定向的形式传递给像 cat 这样的命令。在 cat 命令中,它将重定向操作“<<”和“<<-”传递给命令。这两个操作都允许重定向由 Bash 读取、创建的后续行

cat <<delimeter
     here-document
delimiter

示例:

$ cat <<EOF > print.sh
#!/bin/bash
echo \$PWD
echo $PWD
EOF

print.sh文件中将包含:

#!/bin/bash
echo $PWD
echo /home/user

cat <<EOF 与 cat <<-EOF 的区别

两个都是获取stdin,并在EOF处结束stdin,输出stdout。

在我们使用cat <<EOF时,我们输入完成后,需要在一个新的一行输入EOF结束stdin的输入。EOF必须顶行写,前面不能用制表符或者空格。

如果重定向的操作符是<<-,那么分界符(EOF)所在行的开头部分的制表符(Tab)都将被去除。这可以解决由于脚本中的自然缩进产生的制表符。

here-document
here-document 是一个特殊用途的代码块。它使用一种I/O 重定向形式将命令列表提供给交互式程序或命令,例如ftp、cat或ex文本编辑器。

COMMAND <<InputComesFromHERE
... 
... 
... 
InputComesFromHERE

9. Bash 调试

  • -n 参数
bash -n xxx.sh 

bash的-n选项会读取命令但不执行它们。这可用于检查 shell 脚本的语法错误。这会被交互式 shell 忽略。

  • -x 参数
    “-x”选项可用来跟踪脚本的执行,是调试shell脚本的强有力工具。“-x”选项使shell在执行脚本的过程中把它实际执行的每一个命令行显示出来,并且在行首显示一个”+”号。 “+”号后面显示的是经过了变量替换之后的命令行的内容,有助于分析实际执行的是什么命令。 “-x”选项使用起来简单方便,可以轻松对付大多数的shell调试任务,应把其当作首选的调试手段。
bash -x xxx.sh

shell的执行选项除了可以在启动shell时指定外,亦可在脚本中用set命令来指定。 “set -参数”表示启用某选项,”set +参数”表示关闭某选项。有时候我们并不需要在启动时用”-x”选项来跟踪所有的命令行,这时我们可以在脚本中使用set命令,如以下脚本片段所示:

set -x    #启动"-x"选项 要跟踪的程序段 
set +x     #关闭"-x"选项
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值