Why does the while statement in Shell only loop once?

Source: Internet
Author: User

1. Event Description:

1 ,#! /Bin/bash

Cat ../ip.txt | while read line

Do

Echo $ line

SSH $ line "ls"

Done

The result is recycled once and then exited. The reason is that while uses the redirection mechanism. All the information in the file is read and redirected to the entire while statement. The SSH statement just reads everything in the input. After the SSH statement is called, the input cache has been read. When the read Statement is read again, it cannot read a record and exits cyclically.

2 ,#! /Bin/bash

Cat ../ip.txt | while read line

Do

Echo ------------ $ line

Ls

Done

Exit after normal Loop

#! /Bin/bash

Cat ../ip.txt | while read line

Do

Echo ------------ $ line

Cat

Done

Exit once in a loop. cat prints other records in the file.

Ii. solution:

1. Replace it with the for statement.

#! /Bin/bash

For line in 'cat ../ip.txt'

Do

Echo $ line

SSH $ line "ls"

Done

2. input redirection

#! /Bin/bash

Cat ../ip.txt | while read line

Do

Echo $ line

SSH $ line "ls" </dev/null

Done

This article is from the "linuxdream" blog, please be sure to keep this source http://books.blog.51cto.com/2600359/1554840

Why does the while statement in Shell only loop once?

Related Article

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.