Introduction to Shell Script

Time:2022-8-7

Introduction to Shell Script

Difference from 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 some commands through which users can access the services of the operating system kernel.

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

shell online tool

Shell script is a script program written for Shell, similar to Windows bat script, the difference is that bat is used to operate Windows operating system, while Shell script is used to operate Linux system.

Script programming environment

text editor

Script interpreter capable of interpreting execution

Common interpreters 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)

Bash is generally used, which is the Bourne Again Shell. Bash is also the default shell of most Linux systems.

The #! at the beginning of Shell Script tells the system to interpret the Shell program path of this script file. For example, the execution path of Shell Scirpt below is /bin/bash

#!/bin/bash

First Shell Script

Open a text editor (you can use vi/vim or vs code to write), create a new file test.sh with the extension sh (sh stands for shell), the extension does not affect script execution.

#!/bin/bash
echo "Hello World !"

is a convention mark that tells the system what interpreter this script needs to execute, i.e. which shell to use.
The echo command is used to output text to the window.

There are two ways to run Shell Script:

1. As an executable program

Save the above code as test.sh and cd to the corresponding directory:

chmod +x ./test.sh
./test.sh

Note that it must be written as ./test.sh, not test.sh. The same is true for running other binary programs. Write test.sh directly. The Linux system will go to the PATH to find out if there is a file called test.sh, but only /bin , /sbin, /usr/bin, /usr/sbin, etc. are in the PATH, your current directory is usually not in the PATH, so if you write test.sh, you will not find the command, use ./test.sh to tell the system to say , just look in the current directory.

Introduction to Shell Script

2. As an interpreter parameter

/bin/sh test.sh

Scripts run in this way do not need to specify interpreter information in the first line of the script

The operation effect is as follows:

Introduction to Shell ScriptIntroduction to Shell Script

Introduction to Shell Script