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

2020-05-25  本文已影响0人  javen_spring

if条件句

if command
then
commands
fi  #if条件语句的终止信号
if command
then
commands
else
commands
fi
  1. 数值判断


    数值判断

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

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

for循环语句:批量操作

for 变量 in 范围
do   #类似于if语句的then
命令
done  #类似于if语句的fi
(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
(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 read 变量
do
命令
done
(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

命令组:() 和 {}

(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
上一篇 下一篇

猜你喜欢

热点阅读