loop.sh 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #!/bin/sh
  2. source $(dirname "$0")/test-commons.inc
  3. # go to a writable directory
  4. cd /tmp
  5. singlecommand_ok=yes
  6. multicommand_ok=yes
  7. inlineexec_ok=yes
  8. implicit_ok=yes
  9. infinite_ok=''
  10. break_ok=yes
  11. continue_ok=yes
  12. break_in_infinite_ok=''
  13. # Full form
  14. # Empty
  15. for x in () { }
  16. # Empty block but nonempty list
  17. for x in (1 2 3) { }
  18. # Single command in block
  19. for cmd in ((test 1 = 1) (test 2 = 2)) {
  20. $cmd || unset singlecommand_ok
  21. }
  22. # with index
  23. for index i val in (0 1 2) {
  24. if not test "$i" -eq "$val" {
  25. unset singlecommand_ok
  26. }
  27. }
  28. for index i val in (1 2 3) {
  29. if not test "$i" -ne "$val" {
  30. unset singlecommand_ok
  31. }
  32. }
  33. # Multiple commands in block
  34. for cmd in ((test 1 = 1) (test 2 = 2)) {
  35. test -z "$cmd"
  36. test -z "$cmd" && unset multicommand_ok
  37. }
  38. # $(...) as iterable expression
  39. test_file=sh-test-1
  40. echo 1 > $test_file
  41. echo 2 >> $test_file
  42. echo 3 >> $test_file
  43. echo 4 >> $test_file
  44. lst=()
  45. for line in $(cat $test_file) {
  46. lst=($lst $line)
  47. }
  48. test "$lst" = "1 2 3 4" || unset inlineexec_ok
  49. rm $test_file
  50. # Implicit var
  51. for ((test 1 = 1) (test 2 = 2)) {
  52. $it || unset implicit_ok
  53. }
  54. # Infinite loop
  55. loop {
  56. infinite_ok=yes
  57. break
  58. unset break_ok
  59. }
  60. # 'Continue'
  61. for (1 2 3) {
  62. continue
  63. unset continue_ok
  64. }
  65. # 'break' in infinite external loop
  66. for $(yes) {
  67. break_in_infinite_ok=yes
  68. break
  69. }
  70. if not test $singlecommand_ok { fail Single command inside for body }
  71. if not test $multicommand_ok { fail Multiple commands inside for body }
  72. if not test $inlineexec_ok { fail Inline Exec }
  73. if not test $implicit_ok { fail implicit iter variable }
  74. if not test $infinite_ok { fail infinite loop }
  75. if not test $break_ok { fail break }
  76. if not test $continue_ok { fail continue }
  77. if not test $break_in_infinite_ok { fail break from external infinite loop }
  78. if not test \
  79. "$singlecommand_ok $multicommand_ok $inlineexec_ok $implicit_ok $infinite_ok $break_ok $continue_ok $break_in_infinite_ok" \
  80. = "yes yes yes yes yes yes yes yes" {
  81. fail "Something failed :("
  82. }
  83. # return to original directory
  84. cd -
  85. echo PASS