The pipe cannot change the value of the variable

Source: Internet
Author: User
wqfhenanxc@ubuntu:~$ Cat test.sh
#!/bin/bash
Lines=0
Cat $ | While Read line
Do
((lines++))
Done
echo "Number of lines read is: $Lines"
Exit 0
wqfhenanxc@ubuntu:~$./test.sh
Number of lines Read is:0

wqfhenanxc@ubuntu:~$ Cat test.sh
#!/bin/bash
Lines=0
While Read line
Do
((lines++))
Done <$0
echo "Number of lines read is: $Lines"
Exit 0
wqfhenanxc@ubuntu:~$./test.sh
Number of lines Read Is:8

The above two scripts one uses the pipeline to read the file, one using the redirect to read.
The result is not the same.
Ask for answers from the nature of script execution.

Background knowledge:
1. When I enter./test.sh on the command line, the current shell creates a child shell.
The child shell reads the commands in the test.sh and calls the fork before calling exec for each line of the command.

2. For pipelines, the child shell first creates the pipe descriptor and then fork out the two sub-processes on either side of the pipeline, allowing the output of one child process to be redirected to the input of another child process.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.