[关闭]
@yudesong 2018-02-12T02:53:44.000000Z 字数 1460 阅读 577

Linux Shell 编程

Linux shell


  1. #!/bin/bash
  2. # 使用shell来执行
  3. sh hello.sh
  4. # 使用bash来执行
  5. bash hello.sh
  6. # 使用.来执行
  7. . ./hello.sh
  8. # 使用source来执行
  9. source hello.sh
  10. # 还可以让脚本本有者该执行权限,允许该用户执行该脚本
  11. chmod u+rx hello.sh
  12. # 执行命令,这身就具有可执行权限,通过chmod命令可以修改:
  13. # 赋予脚本的所将使用脚本第一行指定的shell来执行,如果指定shell不存在,将使用系统默认shell来执行
  14. ./hello.sh
  15. # 初始化一个变量
  16. LOG_DIR=/var/log
  17. cd $LOG_DIR
  18. cat /dev/null > wtmp
  19. echo "Logs cleaned up."
  20. exit
  21. # 输入参数
  22. :<<!
  23. read -p "plese input par:" a b
  24. #输出参数
  25. echo $a,$b
  26. #echo ${a},${b}
  27. echo "参数个数为:$#"
  28. echo "脚本名字:$0"
  29. echo "第一个参数:$1"
  30. echo "第二个参数:$2"
  31. !
  32. :<<!
  33. echo "Is it morning? please answer yes or no."
  34. read timeofday
  35. if [ "$timeofday" = "yes" ]
  36. then
  37. echo "Good morning."
  38. elif [ "$timeofday" = "no" ]
  39. then
  40. echo "Good afternoon."
  41. else
  42. echo "Sorry, $timeofday not recognized. Enter yes or no."
  43. exit 1
  44. fi
  45. !
  46. :<<!
  47. for foo in a b c d
  48. do
  49. echo $foo
  50. done
  51. !
  52. n=`cat file.txt | tr -s ' ' '\n' | wc -l`
  53. echo $n
  54. my_array=(A B "C" D)
  55. echo ${my_array[0]}
  56. my_array[0]=A
  57. my_array[1]=B
  58. my_array[2]=C
  59. my_array[3]=D
  60. echo "数组的元素为: ${my_array[*]}"
  61. echo "数组的元素为: ${my_array[@]}"
  62. echo "数组元素个数为: ${#my_array[*]}"
  63. echo "数组元素个数为: ${#my_array[@]}"
  64. for loop in 1 2 3 4 5
  65. do
  66. echo "The value is: $loop"
  67. done
  68. for str in 'This is a string'
  69. do
  70. echo $str
  71. done
  72. int=1
  73. while(( $int<=5 ))
  74. do
  75. echo $int
  76. let "int++"
  77. done
  78. while true
  79. do
  80. command
  81. done
  82. echo '输入 1 到 4 之间的数字:'
  83. echo '你输入的数字为:'
  84. read aNum
  85. case $aNum in
  86. 1) echo '你选择了 1'
  87. ;;
  88. 2) echo '你选择了 2'
  89. ;;
  90. 3) echo '你选择了 3'
  91. ;;
  92. 4) echo '你选择了 4'
  93. ;;
  94. *) echo '你没有输入 1 到 4 之间的数字'
  95. ;;
  96. esac
  97. while :
  98. do
  99. echo -n "输入 1 到 5 之间的数字:"
  100. read aNum
  101. case $aNum in
  102. 1|2|3|4|5) echo "你输入的数字为 $aNum!"
  103. ;;
  104. *) echo "你输入的数字不是 1 到 5 之间的! 游戏结束"
  105. break
  106. ;;
  107. esac
  108. done
  109. while :
  110. do
  111. echo -n "输入 1 到 5 之间的数字: "
  112. read aNum
  113. case $aNum in
  114. 1|2|3|4|5) echo "你输入的数字为 $aNum!"
  115. ;;
  116. *) echo "你输入的数字不是 1 到 5 之间的!"
  117. continue
  118. echo "游戏结束"
  119. ;;
  120. esac
  121. done
  122. exit 0
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注