Open the text editor and create a new file with the extension SH (SH stands for shell). The extension does not affect script execution. If you use PHP to write shell scripts, PHP is enough for the extension.
Enter some code:
1 #!/bin/bash2 echo "Hello World !"
View code
"#!" Is an agreed tag, which tells the system what interpreter is required to execute this script, that is, which shell is used. The echo command is used to output text to the window.
There are two methods to run shell scripts.
As an executable program
Save the above Code as test. SH and CD it to the corresponding directory:
Save the above Code as test. SH and CD it to the corresponding directory:
Chmod + X./test. Sh # grant the script execution permission./test. Sh # execute the script
Note that you must write it as./test. Sh instead of test. Sh. The same is true for running other binary programs. sh, the Linux system will go to the path to find whether it is named test. sh, and only/bin,/sbin,/usr/bin,/usr/sbin and so on in the path. Your current directory is usually not in the path, so it is written as test. sh cannot find the command. /test. sh tells the system to find it in the current directory.
Run the bash script in this way. The first line must be correct so that the system can find the correct interpreter.
Here, the "System" is actually the shell application (IMAGINE Windows Explorer), But I deliberately write it as a system for ease of understanding. Since this system refers to shell, can a script using/bin/sh as the interpreter Save the first line? Yes.
As interpreter Parameter
In this running mode, run the interpreter directly. The parameter is the name of the shell script file, for example:
/bin/sh test.sh/bin/php test.php
This method does not need to specify the interpreter information in the first line.
Let's look at another example. Use the following scriptReadThe command gets the input from stdin and assigns it to the person variable. Finally, the output is on stdout:
#!/bin/bash # Author : mozhiyan# Copyright (c) http://see.xidian.edu.cn/cpp/linux/# Script follows here: echo "What is your name?"read PERSONecho "Hello, $PERSON"
View code
1 #!/bin/bash2 3 # Author : mozhiyan4 # Copyright (c) http://see.xidian.edu.cn/cpp/linux/5 # Script follows here:6 7 echo "What is your name?"8 read PERSON9 echo "Hello, $PERSON"
View code
Run the script:
chmod +x ./test.sh$./test.shWhat is your name?mozhiyanHello, mozhiyan$
Shell tutorial 1? -The first shell script