How to run shell program in linux

王林
王林Original
2020-03-12 14:24:284675browse

How to run shell program in linux

First, let’s take a look at a program test.sh

#!/bin/sh
#this is a test.
cd /tmp
echo "hello,this is a test"

How to execute the program:

1. Make the file have Executable permissions, run the file directly.

The chmod command is used to modify the permissions of files.

x is the permission to make the file executable. Just like we ran the program above.

(Recommended tutorial: linux tutorial)

2. Directly call the command interpreter to execute the program.

How to run shell program in linux

Since our interpreter is /bin/sh, we use the sh command interpreter to execute the program.

3. Use source to execute the file.

How to run shell program in linux

Explanation of program execution differences:

Among the three methods we use to run shell programs, the execution processes of the first two methods are as follows:

(1) The parent process received the command, and then found that it was not a built-in command, so it created a shell process like its own to execute the external command

(2) This shell child process uses /bin /sh replaces itself, and the sh process sets its own running environment variables, including the $PWD variable.

(3) The sh process executes the built-in commands cd and echo in sequence. During this process, the environment variables of the sh process (child process) are changed by the cd command.

(4) After the child process is executed, it dies. The parent process that has been waiting wakes up and continues to accept commands.

So we understand the reason why the execution results of the first two methods are different from our expectations. The current directory (environment variable) of the parent process cannot be changed by the child process.

However, when using source to execute a shell script, the child process will not be created, but will be executed directly in the parent process.

Recommended related video tutorials: linux video tutorial

The above is the detailed content of How to run shell program in linux. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn