Execute shell script method in Linux

There are many ways to bash shell scripting, and now make a summary. Suppose the file name of the shell script we wrote is hello.sh, the file location is in the /data/shell directory and it has execute permission.

 

Method 1: Switch to the directory where the shell script is located (at this time, called the working directory) to execute the shell script:

code show as below:

cd /data/shell
./hello.sh  

./ means to execute hello.sh in the current working directory. Without ./, bash may respond with an error message saying hello.sh could not be found. Because the current working directory (/data/shell) may not be among the default search paths of the executable program, that is, not among the contents of the environment variable PATH. To view the contents of PATH, use the echo $PATH command. The current /data/shell is not in the environment variable PATH, so ./ must be added to execute it.

 

Method 2: Execute the bash shell script with an absolute path:

code show as below:

/data/shell/hello.sh


Method 3: Use bash or sh directly to execute the bash shell script:

code show as below:

cd /data/shell
bash hello.sh

or

cd /data/shell
sh hello.sh
 


Note that if it is executed in the way of method three, then it is not necessary to set the execution authority of the shell in advance, or even write the first line in the shell file (specify the bash path). Because the third method is to pass hello.sh as a parameter to the sh (bash) command to execute. At this time, hello.sh is not executed by itself, but is called to execute by others, so do not execute permissions. Then it's easy to understand without specifying the bash path, huh, huh....

 

Method 4: Execute the bash shell script in the current shell environment:

as follows:

cd /data/shell
.hello.sh

or

cd /data/shell
source hello.sh

When executing the shell script in the first three methods, a sub-shell environment is opened in the current shell (called the parent shell), and the shell script is executed in this sub-shell environment. After the shell script is executed, the subshell environment is closed immediately, and then returned to the parent shell. The fourth method is executed in the current shell.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325339441&siteId=291194637