Simple use of for loop
- 1. Calculate the sum of all integers from 1 to 100
- 2. Filter out the odd and even numbers of all integers from 1 to 100
- 3. Prompt the user to enter an integer less than 100, and calculate the sum of all integers from 1 to this number
- 4. Find the even and odd sums of all integers from 1 to 100
- 5. Detect whether the host in the specified range is communicating, and output the communicating host ip to the file host_ip
- 6. Output all executable files in the /dev directory
- 7. Execute the script to enter the user name, if the user exists, the output prompts that the user already exists; if the user does not exist, prompt the user to enter the password, create the user and set up its password
1. Calculate the sum of all integers from 1 to 100
for ((i=1; i<=100;i++))
do
sum=$[$sum + $i]
done
#!/bin/bash
a=0
for ((i=1; i<=100; i++))
do
a=$(($a+$i))
done
echo $a
2. Filter out the odd and even numbers of all integers from 1 to 100
#!/bin/bash
for ((i=1; i<=100; i++))
do
let a=$i%2
if [ $a = 0 ]
then
echo -e -n "偶数 $i\t"
else
echo "奇数 $i"
fi
done
3. Prompt the user to enter an integer less than 100, and calculate the sum of all integers from 1 to this number
#!/bin/bash
read -p "请输入小于100的整数:" num
a=0
for ((i=1; i<=$num; i++))
do
a=$(($a+$i))
done
echo $a
4. Find the even and odd sums of all integers from 1 to 100
#!/bin/bash
b=0
c=0
for ((i=1; i<=100; i++))
do
let a=$i%2
if [ $a = 0 ]
then
let c=$i+$c
elif [ $a = 1 ]
then
let b=$i+$b
fi
done
echo "$c 为1到100偶数的和"
echo "$b 为1到100奇数的和"
5. Detect whether the host in the specified range is communicating, and output the communicating host ip to the file host_ip
#!/bin/bash
for i in 192.168.100.{110..113}
do
ping -c 3 -i 0.5 -W 2 $i
if [ $? = 0 ]
then
echo $i >> host_ip
else
echo "$i offline"
fi
done
6. Output all executable files in the /dev directory
#!/bin/bash
for i in /dev/*
do
if [ -f $i ]
then
echo "$i 文件存在"
if [ -x $i ]
then
echo "$i 有执行权限"
else
echo "$i 没有执行权限"
fi
else
echo "$i 不是文件"
fi
done
7. Execute the script to enter the user name, if the user exists, the output prompts that the user already exists; if the user does not exist, prompt the user to enter the password, create the user and set up its password
#!/bin/bash
read -p "请输入用户名:" user
useradd $user
if [ $? = 9 ]
then
echo "$user 已存在"
else
read -p "请输入密码:" a
echo "$a" | passwd --stdin $user
fi