Shell script execution mode

Shell script files do not need to be compiled, only need to be parsed by the interpreter. Therefore, the script file with modified permissions can be directly executed. There are three ways to execute Shell scripts.

  1. As an executable program,
    execute the script file test.sh, as shown in the example.
    ./test.sh
linux@ubuntu:~/1000phone$ ./test.sh   //执行脚本文件
hello world                      //脚本文件的输出结果
linux@ubuntu:~/1000phone$

For example, the script file is regarded as a binary executable program, and the execution method is "./xxx.sh". When executing the script, the Linux system will search for the script according to the path specified by the global environment variable PATH, and the path where the current script file is located will not be specified if the PATH is not modified. Therefore, the use of "./" means to notify the system and search in the current directory.

  1. Specify environment variables
    If the user wants to execute Shell script files in a specific directory in any working directory of the system, just add the directory where the Shell script is located to the environment variable PATH.
    Add the path of the script file shown in the example to the entire environment variable. The specific operation is as shown in the example.
linux@ubuntu:~/1000phone$ ls
test.sh                              //脚本文件
linux@ubuntu:~/1000phone$ export PATH=/home/linux/1000phone:$PATH 
//指定脚本文件所在路径
linux@ubuntu:~/1000phone$ cd    //切换到主目录,也可切换到其他任意目录
linux@ubuntu:~$ test.sh        //直接输入脚本文件名即可运行脚本,无需再指定路径
hello world                    //脚本的运行结果
linux@ubuntu:~$

In the above example, the path where the script file test.sh is located is "/home/linux/1000phone". Therefore, use the export command to temporarily add the path to the PATH variable. After adding the path, you can directly enter the file name in any directory to execute the script file without specifying the path.

  1. As an interpreter parameter
    In addition to the above execution method, the user can also choose to run the interpreter directly, the parameter is the script file name, as shown in the example.
linux@ubuntu:~/1000phone$ sh test.sh    //直接运行解释器,将脚本文件作为参数
hello world
linux@ubuntu:~/1000phone$

Execute the script file as shown in the example, without specifying the interpreter information on the first line. If the Shell to be used is bash, replace sh in the example with bash.

Guess you like

Origin blog.csdn.net/anton_99/article/details/102979742