Shell脚本编程入门

最近在学习Shell脚本,两个地方值得注意。

1. Shell中的运算

a=7
b=8
let c=a+b
c=$[a+b]
c=$((a+b))
c=`expr $a + $b`    //``等价于$()

参考:03 Linux shell 变量 数学 运算 

2. Shell中的exec和重定向

我写了一个简单的脚本copy.sh,代码如下

#! /bin/bash 

# read from $1 and write to $2

if [ $# -ne 2 ]
then
    echo "Usage:$0 inputFile outputFile"
fi

inputFile=$1
outputFile=$2

exec 6<&0
exec < $inputFile
 
let count=0 
 
while read line
do
    ((count++)) 
    echo $line >> $outputFile
    if [ $? -ne 0 ]
    then
        echo "Error in writing to file $outputFile" 
    fi
done

echo "Number of lines: $count"
echo "Done"

exec 0<&6 6<&-

部分语句解释如下:

exec 6<&0      # 将文件描述符6与stdin关联

exec < $inputFile    # 用inputFile替代stdin

exec 0<&6 6<&-     # 从文件描述符6中恢复stdin,并关闭文件描述符6

 

参考:

 Shell Script Examples

 linux exec与重定向

原文地址:https://www.cnblogs.com/gattaca/p/6141738.html