Shell

Shell

Shell programming can be accomplished by directly executing shell commands at the shell prompt or by storing them in the order of execution, in a text file, called a shell script, a command-line interpreter (CLI) . To execute, simply write the shell script file name, once the file has execute permission (chmod +x filename).

There is different types of shells, such as sh, bash, zsh etc.

  • The Bourne shell (sh) is regarded as the first UNIX shell ever. The Bourne shell has some major drawbacks, for example it doesn't have in-built functionality to handle logical and arthmetic operations.

  • More popularly known as the Bash shell, the GNU Bourne-Again shell (bash) was designed to be compatible with the Bourne shell. It allows us to automatically recall previously used commands and edit them with help of arrow keys, unlike the Bourne shell.

  • The Z Shell (zsh) is a sh shell extension with more improvements for customization, including some features of Bash.

We will discusses shell programming in general with focus on Bash shell as the main shell interpreter.

Hello, Work!

It is common to name the shell script with the ".sh" extension. And the first line begins with a "sha-bang" (#!) which proclaim where the shell interpreter is located. It like this:

#!/bin/bash

or

#!/usr/bin/env bash

The latter finds bash in current env, lends you some flexibility on different systems. To add a shell command like following:

#!/bin/bash
#!/usr/bin/env bash		# comment

# To print Hello Work!
echo 'Hello Work!'

And any text following the "#" is considered a comment expect "sha-bang" at first line. Excuting this shell programming by:

Variables

Basic

Shell variables are created once are assigned, case sensitive and can consist of a combination of letters and the underscore "_". A variable can contain a number, a character or a string of characters.

Variables can be assigned with the value of a command output, called substitution. Substitution can be done by encapsulating the command with ` `(known as back-ticks) or with $(). When the script runs, it will run the command inside the $()parenthesis or ` ` and capture its output.

Arrays

An array is initialized by assign space-delimited values enclosed in (). Array members need not be consecutive or contiguous. Some members of the array can be left uninitialized.

The array elements can be accessed with their numeric index. The index of the first element is 0.

Special variables

Here are some special variables in shell:

  • $0 - The filename of the current script.

  • $n - The Nth argument passed to script was invoked or function was called.

  • $# - The number of argument passed to script or function.

  • $@ - All arguments passed to script or function.

  • $* - All arguments passed to script or function.

  • $? - The exit status of the last command executed.

  • $$ - The process ID of the current shell. For shell scripts, this is the process ID under which they are executing.

  • $! - The process number of the last background command.

The following shows the defference between $@ and $*:

Operators

Arithmetic

To calculate simple arithmetics on variables should use: $((expression))

The basic operators include:

  • a + b addition (a plus b)

  • a - b substraction (a minus b)

  • a * b multiplication (a times b)

  • a / b division (integer) (a divided by b)

  • a % b modulo (the integer remainder of a divided by b)

  • a ****** b exponentiation (a to the power of b)

String

Length

Extraction Extract substring of length $LEN from $STRING starting after position $POS:

If $LEN is omitted, extract substring from $POS to end of line:

Replacement Replace all/firest/beginning/end or delete occurrences of substring:

File Test

Shell provide you with several useful commands to do some file tests on file system. The file test operators are mostly used in the if clause. The syntax likes below:

Common options are as follows:

  • -e: True if the file exists.

  • -d: True if the file exists and is a directory.

  • -f: True if the file exists and is a regular file.

  • -r: True if the file exists and is readable.

  • -w: True if the file exists and is writable.

  • -x: True if the file exists and is executable.

Expression

Comparisons

Number

String

Decision Making

The shell supports logical decision making. Baisc use:

The expression used by the conditional construct is evaluated to either true or false. The expression can be a single string or variable. A empty string or a string consisting of spaces or an undefined variable name, are evaluated as false.

Logical combination The expression can be a logical combination of comparisons, negation is denoted by !, ogical AND (conjunction) is &&, logical OR (disjunction) is ||. Conditional expressions should be surrounded by double brackets [[ ]]:

Case structure Case structure support more cases:

Loops

for support array or command output results:

while if condition is true, until if condition is false, executes commands:

break and continue, like most language, can be used to control loop execution:

Function

The function syntax likes below:

A function call is equivalent to a command. Parameters may be passed to a function, by specifying them after the function name.

By default all variables are global. You can create a local variables using the local:

Pipelines

Background As we know, under normal circumstances every Linux program has three streams opened when it starts; one for input; one for output; and one for printing diagnostic or error messages. The three as special file descriptors, which are represented by:

  • stdin: 0

  • stdout: 1

  • stderr: 2

By default, stdout and stderr are printed to your terminal, that's why we can see them at all. > operator can help us redirect them to a other file descriptor. For example:

Redirect to stdstream use >&, such as: echo "hello work!" 1>&2. We can referene below to understand stdstream, to avoid stderr print to terminal, I redirect stderr to /dev/null:

Pipes

Pipelines is a way to chain commands and connect stdout from one command to the stdin of the next. By default pipelines redirects standard output only. A pipeline is represented by the pipe character: |. To show pipes, we use a command read,which will help us read from stdin:

If you want to include the standard error need to use the form 2>&1 |:

Built-in

Shell builtin commands are commands that can be executed within the running shell's process. Most builtin commands will be used directly. Some time Shell will use external commands, for example echo. Under macOS echo just support -n option. The following shows how to use builtin echo

Programs

Builtin

&&,||,;

<()

进程替换(Process Substitution)不同于将输出视为字符串的$()。进程替换将输出视为文件流,允许将其直接用作命令需要文件作为输入(<()为输入,>()为输出但很少用)。

--

-- 是一个常用的约定,用于指示后续的参数不应被解释为选项标志(flags)。比如要使用rm删除名为-f的文件,可以这样做:

awk

添加筛选条件:

一个awk给history去重的例子:

dirname

du

envsubst

envsubst会根据环境变量替换模板中的变量,然后生成指定名称的文件。 在MacOS,CentOS等系统中,起包含在gettext工具中。

当文件中有多个变量时,需要制定替换的具体变量名:

find

find可以在指定文件夹中按照文件名查找文件:

利用find还可以对找到的文件进行遍历操作,下面是利用ffmpegflac文件转换成wav文件的例子:

grep

按行查找内容

read

接收控制台输入,并按照指定名称创建参数:

scp

Linux命令行下可以通过scp命令传输文件,添加-r选项可以传输目录

从服务器下载文件

上传本地文件目录到服务器

通过跳板机下载文件到本地

shift

tar & zip

zpi 用于压缩制定的文件, -r选项可以递归压缩目录下的文件:

unzip可以将压缩文件解压缩,-d用于制定解压路径:

trap

trap可以捕获系统信号,比如:

  • Ctrl+C可以触发SIGINT

  • Ctrl+Z可以触发SIGSTOPSIGKILL/SIGSTOP 不会被捕获

  • *Ctrl+D仅仅只是输入EOF,不会触发系统信号

tr & sed

tr按照给定的字符,对标准入进行替换:

sed根据指定的参数修改标准输入并写入标准输出:

Others

goreman

Goreman 是一个Foreman的Go语言的克隆版本,一般在开发过程中的调试多个进程时使用。 安装:

Goreman基于命令行同级目录下的Procfile文件来运行,采用[进程名]:[shell脚本]的格式:

常用命令:

expect

asciinema

asciinema可以记录我们的命令行信息,并生成gif图片:

开始记录:

完成后将会自动在当前目录生成demo.cast文件,保存相关信息。然后根据再根据该文件生成图片:

参数后置

The Silver Searcher

相较于grep的文本搜索,更适合搜索大量的文件搜索。

rename

批量修改文件名

openssl

生成padding格式为pkcs1的私钥(openssl3.x.x开始已经不再支持生成pkcs1的密钥了,需要添加选项-traditional选项):

生成公钥:

jq

jq 是一个强大的json处理工具,基础的用法是直接获取json字段中的某值:

还可以通过一些脚本来处理json中的指定字段,比如将上面这个json中的第一层级的嵌套转义json进行去转义:

ffmpeg

最后更新于

这有帮助吗?