Wednesday, November 6, 2013

Simple loops

Here is a small collection of loops you can perform in the bash shell.
Use CompileOnline (ideone works as well)to run the code.
Paste the following sample data into the input.txt file on CompileOnline and run the loops.

Used resources:
SyntaxHighlighter
CompileOnline ABSG


Aang
Korra
Wang
Eska
Tonraq
Kya
Desna
Senna
Bumi
Raava
Unalaq
Varrik
Vaatu


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
Filename=input.txt


echo "#  for loop redirection with \"<\""
count=0
name=
for k in $(wc -l $Filename | cut -d' ' -f1 | xargs seq)
do
  read name
  echo "=> $name"
  let "count += 1"
  if [ "${name//$'\r'/$''}" == "Bumi" ]; then
    break
  fi
done < "$Filename"
echo "Lines: $count"


echo "#  while loop redirection with pipe"
count=0
name=
cat "$Filename" | while read name
do
  echo "=> $name"
  ((i++))
  if [ "${name//$'\r'/$''}" == "Bumi" ]; then
    break
  fi
done
echo "Lines: $count"


echo "#  while loop redirection with subshell"
count=0
name=
while read name
do
  echo "=> $name"
  let "count += 1"
  if [ "${name//$'\r'/$''}" == "Bumi" ]; then
    break
  fi
done < <(cat "$Filename")
echo "Lines: $count"


echo "#  while loop redirection with \"<\""
count=0
name=
while [ "${name//$'\r'/$''}" != "Bumi" ]  
do
  read name                 
  echo "=> $name"
  let "count += 1"
done < "$Filename"           
echo "Lines: $count"


echo "#  until loop redirection with \"<\""
count=0
name=
until [ "${name//$'\r'/$''}" == "Bumi" ]
do
  read name
  echo "=> $name"
  let "count += 1"
done < "$Filename"
echo "Lines: $count"

echo "#  while loop redirection with exec"
count=0
name=
exec 3<&0                 
exec 0<"$Filename"        
while [ "${name//$'\r'/$''}" != "Bumi" ]
do
  read name               
  echo "=> $name"
  let "count += 1"
done                      
exec 0<&3                 
exec 3<&-                 
echo "Lines: $count"

No comments:

Post a Comment