参考:https://linuxhint.com/30_bash_script_examples/#t1
多动手,才能记住,手脑并用才能成长
第一个linux:
#!/bin/bashecho "hello"
给脚本赋予权限:
chmod +x hello.sh
执行脚本:
./hello.sh
变量:
#!/bin/bash((a=11+11))echo $a
这里a是变量,(()) 里面的会自动计算值。
循环+判断:while+if的用法
#!/bin/basha=trueb=1while [ $a ]doecho $bif [ $b -eq 5 ] ;thenbreak;fi((b++))done
for 循环:
#!/bin/bashfor ((a=10;a>0;a--))doecho $adoneprintf "\n"
输入:(read变量,程序运行到这里会停止 等待用户输入)
#!/bin/bashecho "enter your name"read nameecho "hello $name"
if elif 语句:
#!/bin/bashecho "enter a number"read aif [ $a -eq 1 ];thenecho "1"elif [ $a -eq 2 ];thenecho "2"elif [ $a -eq 3 ];thenecho "3"elseecho "try another"fi
case语句:
#!/bin/bashecho "enter a number"read acase $a in1)echo "1" ;;2)echo "2" ;;3)echo "3" ;;*)echo "not found"esac
for + case 语句如何使用:
#!/bin/bashfor arg in "$@"doindex=$(echo $arg | cut -f1 -d = )val=$(echo $arg | cut -f2 -d = )case $index inX) x=$val ;;Y) y=$val ;;*)esacdone((number=x+y))echo "the number is $number"
字符串截取:
#!/bin/bashStr="Learn Linux from LinuxHint"subStr=${Str:6:5}echo $subStr
${Str:6:5} 意思是从字符串的 第6位开始(包含第6位,截取长度为5的字符串)
简单函数:
#!/bin/bashfunction F1(){echo "hello function"}F1
简单函数 如何添加参数:
#!/bin/bashfunction sum(){sum=$(($1 + $2))echo "$sum"}sum 1 22
获取函数的返回值: sname=$(re)
#!/bin/bashfunction re(){val="$name"echo "$val"}echo "enter your name"read namesname=$(re)echo "$sname"
