一些简单的shell实例

1. for

[root@iZ2zedqr9yeos47fg4uor5Z shellscript]# cat for.sh
#!/bin/bash
echo '======================='
for var in a b c d e
do
  echo $var
done
[root@iZ2zedqr9yeos47fg4uor5Z shellscript]# ./for.sh
=======================
a
b
c
d
e

2. array

[root@iZ2zedqr9yeos47fg4uor5Z shellscript]# cat array.sh
#!/bin/bash
array_name=(123 456 789)
for item in ${array_name[@]}
do
  echo ${item}
done
[root@iZ2zedqr9yeos47fg4uor5Z shellscript]# ./array.sh
123
456
789
[root@iZ2zedqr9yeos47fg4uor5Z shellscript]#

3. function

函数方式,外部传参求和

[root@iZ2zedqr9yeos47fg4uor5Z shellscript]# cat function.sh
#!/bin/bash

function demo3(){
    
    
  param1=$1
  param2=$2
  return `expr $param1 + $param2`
}

echo "函数执行开始"
demo3 $1 $2
demo3Return=$?
echo $demo3Return
echo "函数执行结束"
[root@iZ2zedqr9yeos47fg4uor5Z shellscript]# ./function.sh 12 23
函数执行开始
35
函数执行结束
[root@iZ2zedqr9yeos47fg4uor5Z shellscript]#

4. 读文件的综合示例

逐行读取外部文件,去掉每行的左右空格,给每一行加上" ", 最后一行不加,

[root@iZ2zedqr9yeos47fg4uor5Z shellscript]# cat b.txt
a bc

d

e
 f
 d
 h
i
[root@iZ2zedqr9yeos47fg4uor5Z shellscript]# cat readFile.sh
#!/bin/bash
IFS=""
readFilePath=$1
lineNumber=0

if [[ ! -e $readFilePath || -z $readFilePath ]]
then
   echo "文件路径未指定或文件$readFilePath不存在,脚本不需继续执行"
   exit
fi

echo "准备读取文件:$readFilePath"
lineTotal=$(cat $readFilePath | wc -l)
echo "文件总行数:$lineTotal"
echo "===================================="
cat $readFilePath | while read line
do
  lineNumber=`expr $lineNumber + 1`
  if [ -z $line ]
  then
#     echo "该行为空"
     continue
  fi
  lineData=$(echo $line | sed -e 's/^[ ]*//g' | sed -e 's/[ ]*$//g')
  lineData=\"$lineData\"
  if [ $lineNumber != $lineTotal ]
  then
    lineData=$lineData,
  fi
  echo $lineData
done
[root@iZ2zedqr9yeos47fg4uor5Z shellscript]# ./readFile.sh b.txt
准备读取文件:b.txt
文件总行数:9
====================================
"a bc",
"d",
"e",
"f",
"d",
"h",
"i"
[root@iZ2zedqr9yeos47fg4uor5Z shellscript]#

猜你喜欢

转载自blog.csdn.net/qq_39198749/article/details/127320761