[Shell] how to execute a shell script

I hope not white piao, the point of a brush praise or comments to walk, as well as prohibit [Reserved]
This article is to explain how to execute a shell script, as well as different ways of how to execute the script calls. And understanding sh xxx.sh and source the difference xxx.sh (note I do more, made only slowly, if there is a particular need a certain aspect, you can reply in the comments, if I have the relevant information I will give priority to the issue)
@note : If you do not write a shell script, I see another article fool to write shell

How to execute a shell script

Execute scripts

Write a simple script test.sh:
#! /bin/sh
cd ..
ls
Shell script using the # denotes a comment, the comment is equivalent // C language. However, if at the beginning of the first row #, # and is! (Referred to as the Shebang) The exception, which indicates that the script interpreter specified later / bin / sh interpreted . If this script file with executable permissions and then execute:
chmod a+x test.sh
./test.sh
Shell will fork a child process and execution ./test.sh this program calls exec, exec system call should handle process code segment replace ./test.sh program code segments, and started from its _start. However test.sh is a text file, there is no code and _start function, how to do it? In fact, there is another mechanism exec, if you want to perform a text file, and the first line specifies an interpreter with Shebang, it is replaced with the current process code segment interpreter program and start from _start interpreter execution , and this is a text file as a command line argument to the interpreter. Therefore, the equivalent of executing the script execution procedures
/bin/sh ./test.sh
do not need test.sh file in this manner have executable permissions.
If the command line with the input () parentheses, it will fork a child parentheses Shell execution command may be input by a semicolon line; a plurality of spaced command, such as:
(cd ..;ls -l)
above two Shell script execution method effect is the same, cd ... Shell command to change a child's PWD, but will not affect the interactive Shell . However, the command
cd ..;ls -l
has a different effect, cd ... command is executed directly in the interactive Shell, change the PWD interactive Shell, but this way is equivalent to the implementation of this Shell script:
source ./test.sh
or
. ./test.sh
source, or a Shell builtin command. this way it will not create sub Shell, but directly commands in the script line by line in an interactive Shell.(Source command does not create a sub-shell)

Published 21 original articles · won praise 20 · views 1876

Guess you like

Origin blog.csdn.net/weixin_43071838/article/details/104493917