您的位置:首页 > 运维架构 > Shell

Shell脚本编程入门

2016-12-07 16:35 399 查看
最近在学习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与重定向

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: