bash 几个常用的代码
#########最简单的bash
#! /bin/bash #解析器路径 env #查看环境
##########看运行时间
#!/bin/bash #文件名: time.sh start=$(date +%s) #commands; #statements; sleep 10; #command end=$(date +%s) difference=$(( end - start)) echo Time taken to execute $0 is $difference seconds.
########## while循环
#!/bin/bash declare -i i=1 declare -i sum=0 while ((i<=10)) do let sum+=i let ++i done echo $sum
########## 关于中断光标
#!/bin/bash #文件名: sleep.sh echo -n Count: # tput sc存储光标位置 tput sc count=0; while true; do if [ $count -lt 40 ]; then let count++; sleep 1; # 恢复光标位置的命令是tput rc tput rc # tput ed清除从当前光标位置到行尾之间的所有内容 tput ed echo -n $count; else exit 0; fi done
############shell判断
#! /bin/bash declare -i num=0 if [ $num -lt 0 ] #一定要注意在[或]与操作数之间有一个空格 then echo "<"; elif [ $num -eq 0 ] then echo "=="; else echo ">"; fi # [ $var1 -ne 0 -a $var2 -gt 2 ] #使用逻辑与-a # [ $var1 -ne 0 -o var2 -gt 2 ] #逻辑或 -o
############shell Debug
#!/bin/bash #文件名: debug.sh for i in {1..6}; do set -x echo $i set +x done echo "Script executed"
############break
#!/bin/bash while : do echo -n "Input a number between 1 to 5: " read aNum case $aNum in 1|2|3|4|5) echo "Your number is $aNum!" ;; *) echo "You do not select a number between 1 to 5, game is over!" break ;; esac done
##############case
#! /bin/bash echo ‘Input a number between 1 to 4‘ echo ‘Your number is:\c‘ read aNum case $aNum in 1) echo ‘You select 1‘ ;; 2) echo ‘You select 2‘ ;; 3) echo ‘You select 3‘ ;; 4) echo ‘You select 4‘ ;; *) echo ‘You do not select a number between 1 to 4‘ ;; esac
#########function
function fname() { echo $1, $2; #访问参数1和参数2 echo "[email protected]";#以列表的方式一次性打印所有参数 echo "$*"; #类似于[email protected],但是参数被作为单个实体 return 0; #返回值 } fname arg1 arg2 arg3 export -f fname
时间: 2024-10-27 19:10:50