1. utilize while Cycle calculation 1 reach 100 And :
Sample code 1:
#!/bin/bash
i=1
sum=0
while [ $i -le 100 ]
do
let sum=sum+$i
let i++
done
echo $sum
Sample code 2: utilize while Cycle calculation 1 reach 100 The sum of all odd numbers between
#!/bin/bash
i=1
sum=0
while [ $i -le 100 ]
do
let sum=sum+$i
let i+=2
done
echo $sum
Sample code 3: utilize while Cycle calculation 1 reach 100 Sum of all even numbers between
#!/bin/bash
i=2
sum=0
while [ $i -le 100 ]
do
let sum=sum+$i
let i+=2
done
echo $sum
2. utilize while Circular printing **
Sample code : utilize while Cycle one 5x5 Of *
#!/bin/bash
i=1
j=1
while [ $i -le 5 ]
do
while [ $j -le 5 ]
do
echo -n "* "
let j++
done
echo
let i++
let j=1
done
3. use read combination while Loop through text file :
Sample code 1:
#!/bin/bash
file=$1 # Position parameter 1 Copy the file name of to file
if [ $# -lt 1 ];then # Determine whether the user has entered the location parameters
echo "Usage:$0 filepath"
exit
fi
while read -r line # from file The read file content in the file is assigned to line( Using parameters r Special symbols in text will be masked , Only output, not translation )
do
echo $line # Output file content
done < $file
Examples 2: Read file contents by column
#!/bin/bash
file=$1
if [[ $# -lt 1 ]]
then
echo "Usage: $0 please enter you filepath"
exit
fi
while read -r f1 f2 f3 # Divide the contents of the document into three columns
do
echo "file 1:$f1 ===> file 2:$f2 ===> file 3:$f3" # Output file contents by column
done < "$file"
4.while Dead loop in loop :
Examples : Using the dead cycle , Let users choose , Print the results according to the customer's choice
#!/bin/bash
# Print menu
while :
do
echo "********************"
echo " menu "
echo "1.tima and date"
echo "2.system info"
echo "3.uesrs are doing"
echo "4.exit"
echo "********************"
read -p "enter you choice [1-4]:" choice
# According to the customer's choice to do the corresponding operation
case $choice in
1)
echo "today is `date +%Y-%m-%d`"
echo "time is `date +%H:%M:%S`"
read -p "press [enter] key to continue..." Key # Pause the cycle , Prompt customer to press enter Key to continue
;;
2)
uname -r
read -p "press [enter] key to continue..." Key
;;
3)
w
read -p "press [enter] key to continue..." Key
;;
4)
echo "Bye!"
exit 0
;;
*)
echo "error"
read -p "press [enter] key to continue..." Key
;;
esac
done
Technology
Daily Recommendation