概述:shell常用代码总结
helloword入门
#!/bin/bash
# 指定解析器
echo "helloworld"
echo $A
多命令处理
#!/bin/bash
# 多个命令
cd /home/machine/file
touch "f01d02.txt"
echo "hello BD" >> f01d02.txt
shell变量
#!/bin/bash
# 0是$0 代表该脚本名称,$1-$9 代表第一到第九个参数,十以 上的参数,十以上的参数需要用大括号包含,如${10}
echo "A $0 $1 $2"
# 获取所有输入参数个数
echo $#
# 代表命令行中所有的参数
echo $*
echo $@
if 判断
demo1
#!/bin/bash
if [ $1 -eq "1" ]
then
echo "hello A"
elif [ $1 -eq "2" ]
then
echo "hello B"
fi
demo2
#!/bin/bash
if [ -f $1 ]
then
echo "文件存在!"
else
echo "文件不存在!"
fi
case 语句
#!/bin/bash
case $1 in
"1")
echo "hello A"
;;
"2")
echo "hello B"
;;
*)
echo "no"
;;
esac
for 循环
demo1
#!/bin/bash
# 从1加到100
s=0
for((i=1;i<=100;++i))
do
s=$[ $s + $i ]
done
echo $s
demo2
#!/bin/bash
# 打印所有输入参数
for i in $*
do
echo "hello $i"
done
for i in "$*"
do
echo "hello $i"
done
for i in $@
do
echo "hello $i"
done
for i in "$@"
do
echo "hello $i"
done
while 循环
#!/bin/bash
# 从1加到100
s=0
i=0
while [ $i -le 100 ]
do
s=$[ $s + $i ]
i=$[ $i + 1 ]
done
echo $s
read 读取控制台输入
#!/bin/bash
read -t 7 -p "Enter your name in 7 seconds: " NAME
echo $NAME
函数
#!/bin/bash
# 计算两个输入参数的和
function sum(){
s=0
s=$[ $1 + $2 ]
echo "$s"
}
read -p "Please input the number1: " n1
read -p "Please input the number2: " n2
sum $n1 $n2
shell工具
包括:cut、sed、awk、sort
$ cut -d " " -f 1 cut.txt
$ sed -e '2d' -e 's/wo/ni/g' sed.txt
$ wk -F : 'BEGIN{print "user, shell"} {print $1","$7} END{print "dahaige,/bin/zuishuai"}'
$ sort -t : -nrk 3 sort.sh