1 #!/bin/bash 2 3 # 小技巧: 4 # 如果你不确定某一条件怎么被求值, 5 #+ 可以用一个if-test结构来测试. 6 7 echo 8 9 echo "Testing \"0\"" 10 if [ 0 ] # 0 11 then 12 echo "0 is true." 13 else 14 echo "0 is false." 15 fi # 0为真. 16 17 echo 18 19 echo "Testing \"1\"" 20 if [ 1 ] # 1 21 then 22 echo "1 is true." 23 else 24 echo "1 is false." 25 fi # 1为真. 26 27 echo 28 29 echo "Testing \"-1\"" 30 if [ -1 ] # -1 31 then 32 echo "-1 is true." 33 else 34 echo "-1 is false." 35 fi # -1为真. 36 37 echo 38 39 echo "Testing \"NULL\"" 40 if [ ] # NULL (空条件) 41 then 42 echo "NULL is true." 43 else 44 echo "NULL is false." 45 fi # NULL为假. 46 47 echo 48 49 echo "Testing \"xyz\"" 50 if [ xyz ] # 字符串 51 then 52 echo "Random string is true." 53 else 54 echo "Random string is false." 55 fi # 任意字符串为true. 56 57 echo 58 59 echo "Testing \"\$xyz\"" 60 if [ $xyz ] # 变量$xyz为null值, 但... 61 # 它只是一个未初始化的变量. 62 then 63 echo "Uninitialized variable is true." 64 else 65 echo "Uninitialized variable is false." 66 fi # 未初始化的变量为false. 67 68 echo 69 70 echo "Testing \"-n \$xyz\"" 71 if [ -n "$xyz" ] # 进一步实验核实. 72 then 73 echo "Uninitialized variable is true." 74 else 75 echo "Uninitialized variable is false." 76 fi # 未始初化的变量为false. 77 78 echo 79 80 81 xyz= # 已初始化, 但设置成null值. 82 83 echo "Testing \"-n \$xyz\"" 84 if [ -n "$xyz" ] 85 then 86 echo "Null variable is true." 87 else 88 echo "Null variable is false." 89 fi # Null值变量为假. 90 91 92 echo 93 94 95 # 什么时候"false"为真? 96 97 echo "Testing \"false\"" 98 if [ "false" ] # "false"是一个字符串. 99 then 100 echo "\"false\" is true." #+ 它被测试为真. 101 else 102 echo "\"false\" is false." 103 fi # "false"为真. 104 105 echo 106 107 echo "Testing \"\$false\"" # 再来,未初始化的变量. 108 if [ "$false" ] 109 then 110 echo "\"\$false\" is true." 111 else 112 echo "\"\$false\" is false." 113 fi # "$false"变量为假. 114 # 现在, 我们取得了预期的效果. 115 116 # 如果我们测试未初始化的变量"$true"会发生什么? 117 118 echo 119 120 exit 0
bash shell if-test
最新推荐文章于 2023-09-06 15:25:41 发布