优秀的编程知识分享平台

网站首页 > 技术文章 正文

Linux脚本编程——shell脚本基础2

nanyue 2024-07-18 03:51:56 技术文章 7 ℃

Linux脚本编程——shell脚本基础2

1 shell脚本的函数

shell的函数使用关键字 function 来定义,引用的时候直接函数名即可,函数也可以携带参数。

#定义函数 my_func
function my_func(){
    lscpu << cpu_log.txt
    uname -a >> cpu_log.txt
    free -h >> cpu_log.txt
}
#调用函数 my_func
my_func

#定义函数 my_func1 ,携带参数
function my_func1(){
    lscpu >> $1
    uname -a >> $1
    free -h >> $1
}
#调用函数 my_func
my_func1 output.file
my_func1 other_output.file

2 跨文本调用

类似 C 语言的 include 将其他文件的函数调用到本文件,shell 脚本可以使用 source 关键字来实现。

source test.sh
my_func1 my_info.txt

3 测试逻辑

test 语句,对选项两边的表达式进行比较

#数值比较
#大于
test 3 -gt 2; echo $?
#小于
test 3 -lt 2; echo $?
#等于
test 3 -eq 3; echo $?
#不等于
test 3 -ne 1; echo $?
#大于等于
test 5 -ge 2; echo $?
#小于等于
test 3 -le 1; echo $?

#文本比较
#相同
test abc = abx; echo $?
#不同
test abc != abx; echo $?
#按词典顺序,一个文本在另一个前面
test apple > tea; echo $?
#按词典顺序,一个文本在另一个后面
test apple < tea; echo $?

#文件判断
#文件存在
test -e a.out; echo $?
#文件存在,且是普通文件
test -f file.txt; echo $?
#文件夹存在
test -d myfiles; echo $?
test -L a.out; echo $?
#文件可读
test -r file.txt; echo $?
#文件可写
test -w file.txt; echo $?
#文件可执行
test -x file.txt; echo $?

#逻辑组合运算
#非
! expression
#与
expression1 -a expression2
#或
expression1 -o expression2

4 if判断结构

shell 脚本里的 if else 结构,从而实现根据条件来决定是否执行某一部分程序,其中 else 可选,if 判断语句的结尾用 fi 来表示。

shell 脚本里的 if 语句也是可以嵌套的 。

如下实现对当前用户的判断,实现各自的一部分功能。

cur_user=`whoami`
if [ ${cur_user} = "root" ]
then
    echo "you are root"
    echo "you are my god"
else
    echo "you are $cur_user"
fi

5 case分支结构

case 语句实现多程序块的选择执行,case 语句使用 esac 结尾。

cur_user=`whoami`
case $cur_user in
root)
    echo "you are God."
;;
sixer)
    echo "you are a happy user."
;;
*)
    echo "you are the others."
;;
esac

6 while循环结构

shell 会循环执行属于 while 语句里的代码块,知道 while 的逻辑表达式不成立。

now=`date +'%Y%m%d%H%M'`
deadline=`date --date='1 hour' +'%Y%m%d%H%M'`
while [ $now -lt $deadline ]
do
    date
    echo "not yet"
    sleep 10
    now=`date +'%Y%m%d%H%M'`
done
echo "now, deadline reached"

7 for循环结构

指定次数循环执行。

for user in vamei sixer zac
do
    echo $user
done
#配合使用 seq 命令
for var in `seq 1 2 10`
do
    echo $var
done

8 使用循环计算1~100的和

#for语句编写
total=0
for num in `seq 1 1 100`
do
    total=$(( $total + $num))
done

#while语句编写
total1=0
num1=1
while :
do
    if [ $num1 -gt 100 ]
    then
        break
    fi
    total1=$(( $total1 + $num1))
    num1=$(( $num1 + 1))
done
echo $total1

9 公众号

InsertingAll

Tags:

最近发表
标签列表