Skip to content

Instantly share code, notes, and snippets.

@arrayadd
Last active June 17, 2017 10:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arrayadd/6b20e7b05c44916789dc3a742f4e36de to your computer and use it in GitHub Desktop.
Save arrayadd/6b20e7b05c44916789dc3a742f4e36de to your computer and use it in GitHub Desktop.
【Linux】for,while读取每一行的区别

平时要操作线上数据库,只能通过跳板机来连接到生产数据库,然后执行一些sql. 例如,运营同学会筛选出一批活动id,我们需要批量修改下这些id对应的数据过期时间信息,通常我们只需要连接到数据库执行类似update t_activity set ent_time=1234554 where activit_id in (xx,xxx,xx) 的sql就行。

但有时候,运营同学给的id文件中,有几百,上千个。如果我们手动把这些id,用逗号隔开,一个一个拼接到sql中,然后复制这条sql,去执行。就会非常麻烦。这时候下面简单脚步就可以快速搞定。


读取文件的每一行

shell 中读取文件的每一行,有很多实现方式,但fro,While循环的方式是最容易理解的,接近平时编程语言方式。

  • for 方式
for line in `cat file.txt`
do
echo ${line}
done
  • while 方式
cat file.txt | while read line
do
echo ${line}
done

两者有区别

假如上面file.txt文件的内容如下:

111
222
333 444
555  666

上面文件总共3行,但注意第三行中,333 444有1个空格,555 666之间有2个空格。

  1. 如果用for的方式的话,输出的结果会变成4行,如下:
111
222
333
444
555
666

所以,如果你的文件中数据并非都在一行排列,且之间空格不固定,选择for是不错的,

  1. 如果用while的方式的话,输出的结果和原文一样,如下:
111
222
333 444
555 666  //原来的2个空格变成一个了。

所以如上,如果你的文件要按照行读取,且忽略多个空格变为一个空格,while是不错的选择。


开头问题解决方法

读取运营提供id的文件每一行,然后分别执行sql。如下:

#!/bin/bash

while read line
do
#连接mysql执行sql, line 就是每一个行内容
mysql -h xx -pxxx ... -e "update t_activity set end_time=1231 where activit_id=${line}"

done < file.txt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment