Basic usage of Shell

Shell is a program written in C language, which is a bridge for users to use Linux. Shell is both a command language and a programming language.

Shell refers to an application program that provides an interface through which users access the services of the operating system kernel.

Ken Thompson's sh is the first Unix shell, and Windows Explorer is a typical graphical interface shell.

1. Shell script

Shell script (shell script) is a script program written for the shell.

The shell mentioned in the industry usually refers to shell scripts, but readers should know that shell and shell script are two different concepts.

Due to customary reasons, for the sake of brevity, "shell programming" in this article refers to shell script programming, not to the development shell itself.

2. Shell environment

Shell programming is the same as JavaScript and php programming, as long as there is a text editor that can write code and a script interpreter that can interpret and execute.

There are many types of Linux Shells, the common ones are:

  • Bourne Shell (/usr/bin/sh or /bin/sh)
  • Bourne Again Shell(/bin/bash)
  • C Shell(/usr/bin/csh)
  • K Shell(/usr/bin/ksh)
  • Shell for Root(/sbin/sh)

3. The first shell script

Open a text editor (you can use the vi/vim command to create a file), create a new file test.sh, the extension is sh (sh stands for shell), the extension does not affect the script execution, just know the name, if you Use php to write shell scripts, just use php as the extension.

Enter some code, the first line is usually like this:

#!/bin/bash
echo "Hello World !"
复制代码

#! Is a conventional mark, which tells the system what interpreter this script needs to execute, that is, which shell to use.

The echo command is used to output text to the window.

运行 Shell 脚本有两种方法:

1、作为可执行程序

将上面的代码保存为 test.sh,并 cd 到相应目录:

chmod +x ./test.sh  #使脚本具有执行权限
./test.sh  #执行脚本
复制代码

注意,一定要写成 ./test.sh,而不是 test.sh,运行其它二进制的程序也一样,直接写 test.sh,linux 系统会去 PATH 里寻找有没有叫 test.sh 的,而只有 /bin, /sbin, /usr/bin,/usr/sbin 等在 PATH 里,你的当前目录通常不在 PATH 里,所以写成 test.sh 是会找不到命令的,要用 ./test.sh 告诉系统说,就在当前目录找。

2、作为解释器参数

这种运行方式是,直接运行解释器,其参数就是 shell 脚本的文件名,如:

/bin/sh test.sh
/bin/php test.php
复制代码

这种方式运行的脚本,不需要在第一行指定解释器信息,写了也没用。

ubuntu(linux)下 source、sh、bash、./ 执行脚本的区别是什么?

1. source命令用法:

source FileName
复制代码

作用:在当前 bash 环境下读取并执行 FileName 中的命令。该 filename 文件可以无 "执行权限"。

注:该命令通常用命令 . 来替代。

2. sh、bash的命令用法:

sh FileName
bash FileName
复制代码

作用:打开一个子 shell 来读取并执行 FileName 中命令。该 filename 文件可以无 "执行权限"。

注:运行一个shell脚本时会启动另一个命令解释器。

3、./的命令用法:

./FileName
复制代码

作用: 打开一个子 shell 来读取并执行 FileName 中命令,该 filename 文件需要 "执行权限"。

注:运行一个 shell 脚本时会启动另一个命令解释器。

Guess you like

Origin juejin.im/post/7229318874806321212