美文网首页
linux学习笔记---4:if,for,while,命令组

linux学习笔记---4:if,for,while,命令组

作者: javen_spring | 来源:发表于2020-05-25 17:29 被阅读0次

    if条件句

    • if-then语句:
    if command
    then
    commands
    fi  #if条件语句的终止信号
    
    • if-then-else语句:
    if command
    then
    commands
    else
    commands
    fi
    
    • if 条件语句的常见用法: 数值判断,字符串判断,文件判断
    1. 数值判断


      数值判断

    将状态变量返回结果与数值进行比较:

    if [ $? eq 0 ]
    then
    touch ok.txt
    fi
    
    if命令与其他命令结合
    1. 字符串判断(用的较少)
    字符串判断
    1. 文件判断
    文件判断

    for循环语句:批量操作

    • for循环语句的常见格式
    for 变量 in 范围
    do   #类似于if语句的then
    命令
    done  #类似于if语句的fi
    
    • for批量创建文件:
    (base) May5 16:29:16 ~
    $ for i in {1..10}
    > do 
    > touch file${i}.txt
    > done
    (base) May5 16:30:17 ~
    $ ls
    Data        file1.txt  file3.txt  file5.txt  file7.txt  file9.txt   teach
    file10.txt  file2.txt  file4.txt  file6.txt  file8.txt  miniconda3
    
    • $(command) 命令替换,可赋值给变量
    (base) May5 16:39:19 ~
    $ for i in $(ls file*)
    > do 
    > mv ${i} ${i%.*}   #把文件后的.txt后缀去掉
    > done
    (base) May5 16:45:02 ~
    $ ls
    Data  file1  file10  file2  file3  file4  file5  file6  file7  file8  file9  miniconda3  teach
    

    while循环语句:批量操作

    • while循环语句的常见格式
    while read 变量
    do
    命令
    done
    
    • 与for循环相似,批量创建文件
    (base) May5 16:48:07 ~
    $ ls file*
    file1  file10  file2  file3  file4  file5  file6  file7  file8  file9
    (base) May5 16:51:34 ~
    $ ls file* | while read id
    > do
    > mv $id ${id}.txt
    > done
    (base) May5 16:53:49 ~
    $ ls file*
    file10.txt  file1.txt  file2.txt  file3.txt  file4.txt  file5.txt  file6.txt  file7.txt  file8.txt  file9.txt
    

    命令组:() 和 {}

    • () 的命令组:相当于一个小的shell环境,与外部变量无关
    (base) May5 16:54:24 ~
    $ a=abc
    (base) May5 16:58:06 ~
    $ (a=xyz;echo $a)
    xyz
    (base) May5 16:58:22 ~
    $ echo $a
    abc
    
    • {}的命令组:相当于将命令组合起来,与外部变量连续。命令与大括号之间应有空格
    (base) May5 17:00:43 ~
    $ a=abc
    (base) May5 17:07:15 ~
    $ { a=xyz; echo $a; }
    xyz
    (base) May5 17:07:29 ~
    $ echo $a
    xyz
    

    相关文章

      网友评论

          本文标题:linux学习笔记---4:if,for,while,命令组

          本文链接:https://www.haomeiwen.com/subject/fvuyahtx.html