loop format in bash script

  • مدل اول
for (( i=1 ; i <= 10 ; i++ )) ; do
echo $i
done

  • مدل دوم
for VARIABLE in 1 2 3 4 5 .. N
do
	command1
	command2
	commandN
done

  • مدل سوم
for VARIABLE in file1 file2 file3
do
	command1 on $VARIABLE
	command2
	commandN
done

  • مدل چهارم
for OUTPUT in $(Linux-Or-Unix-Command-Here)
do
	command1 on $OUTPUT
	command2 on $OUTPUT
	commandN
done

  • مدل پنجم
#!/bin/bash
for i in 1 2 3 4 5
do
   echo "Welcome $i times"
done

  • مدل ششم
#!/bin/bash
for i in {1..5}
do
   echo "Welcome $i times"
done

  • مدل هفتم
#!/bin/bash
echo "Bash version ${BASH_VERSION}..."
for i in {0..10..2}
  do 
     echo "Welcome $i times"
 done

  • مدل هشتم
#!/bin/bash
for i in $(seq 1 2 20)
do
   echo "Welcome $i times"
done

  • مدل نهم
#!/bin/bash
for (( ; ; ))
do
   echo "infinite loops [ hit CTRL+C to stop]"
done

  • مدل دهم
#!/bin/bash
for file in /etc/*
do
	if [ "${file}" == "/etc/resolv.conf" ]
	then
		countNameservers=$(grep -c nameserver /etc/resolv.conf)
		echo "Total  ${countNameservers} nameservers defined in ${file}"
		break
	fi
done

  • مدل یازدهم
#!/bin/bash
FILES="$@"
for f in $FILES
do
        # if .bak backup file exists, read next file
	if [ -f ${f}.bak ]
	then
		echo "Skiping $f file..."
		continue  # read next file and skip the cp command
	fi
        # we are here means no backup file exists, just use cp command to copy file
	/bin/cp $f $f.bak
done

 

دیدگاهتان را بنویسید

نشانی ایمیل شما منتشر نخواهد شد. بخش‌های موردنیاز علامت‌گذاری شده‌اند *