Shell script basics ----- For Loop

Source: Internet
Author: User

Format

For name in list

Do

Loop body

Done


Example:

List the usernames, uid, and shell in the/etc/passwd file, Row 1, 3, 6, and 12

#!/bin/bashfor line in 1 3 6 12do        Username=$(head -$line /etc/passwd | tail -1 | awk -F: ‘{print $1}‘)        Userid=$(head -$line /etc/passwd | tail -1 | awk -F: ‘{print $3}‘)        Usershell=$(head -$line /etc/passwd | tail -1 | awk -F: ‘{print $7}‘)        echo -e "UserName:$Username\tUserID:$Userid\tUserShell:$Usershell"done

List generation

1. Give/etc/fstab/etc/inittab one by one

2. wildcard matching, for example,/var /*

3. Command production list

Example:

#!/bin/bashfor File in `ls /var`do    file /var/$Filedone

4. The number sequence {1 .. 100} is automatically expanded to 1 to 100.

{Start number... end number}

SEQ automatically generates a numerical sequence:

Sed 3: generated from 1 to 3

Sed 3 16 production from 3 to 16

Sed 3 2 16 generates 3 to 16, but the interval is 2

3 5 7 9 11 13 15

Exercise: display the usernames and shells of all/etc/passwd users.

#!/bin/bashLINES=$(wc -l /etc/passwd | awk -F" " ‘{print $1}‘)for I in $(seq 1 $LINES)do        head -$I /etc/passwd | tail -1 | awk -F: ‘{print $1,$7}‘done

Arithmetic Operations in shell scripts

Shell does not support floating point numbers: In the calculation result, the floating point will be an integer.

1.22 = 1; 1.99 = 1

Arithmetic Operation Implementation Method

$ [Expression]

For example

A = 1

B = 2

C = $ [$ A + $ B]

Echo $ C

3

Script contact

Calculate the sum of 0 to 100

#!/bin/bashsum=0for i in $(seq 0 100)do        sum=$[$sum+$i]doneecho $sum

Calculate the total uid of all users

#!/bin/bashidsum=0for i in $(awk -F: ‘{print $3}‘ /etc/passwd)do        idsum=$[$idsum+$i]doneecho $idsum


This article from the "hanging sword" blog, please be sure to keep this source http://sublime.blog.51cto.com/8856101/1440022

Shell script basics ----- For Loop

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.