#!/bin/bash
if [ ! -n "$1" ] ;then
echo "you have not input a word!"
else
echo "the word you input is $1"
fi
# 也可以使用test
#!/bin/bash
if test -z $1; then
echo "you have not input a word!"
else
echo "the word you input is $1"
fi
6. 循环
# for语句格式
for 变量名 in 取值列表; do
命令
done
# 比如
#!/bin/bash
for i in {1..3}; do
echo $i
done
# 也可以这样
#!/bin/bash
for ((i=1; i<=3; i++)); do
echo $i
done
# 遍历当前文件夹
#!/bin/sh
for file in ./*
do
if test -d $file
then
cd $file
git pull
echo "$file pull finished!"
cd ..
fi
done
# while语句格式
while 条件表达式; do
命令
done
# 比如
#!/bin/bash
N=0
while [ $N -lt 5 ]; do
let N++
echo $N
done
# 逐行读取文本
# 方式 1:
#!/bin/bash
cat ./a.txt | while read LINE; do
echo $LINE
done
# 方式 2:
#!/bin/bash
while read LINE; do
echo $LINE
done < ./a.txt
# 方式 3:
#!/bin/bash
exec < ./a.txt # 读取文件作为标准输出
while read LINE; do
echo $LINE
done
shell实战实例
从另一个文件中拷贝100份并 替换指定字符
#!/bin/sh
for i in {0..99}; do
while read line || [[ -n $line ]]; do # [[ ]]解决读取不到文件的最后一行
POSTFIX="_$i"
LINE=${line/_0/$POSTFIX} # 将_0替换成_i
echo $LINE >> ./chat_msg_open.sql
done < ./chat_msg.sql
echo -e "\n" >> ./chat_msg_open.sql # -e 使echo支持转移符--换行
done