zoukankan      html  css  js  c++  java
  • 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与重定向

  • 相关阅读:
    4-10
    4-9
    第三章例3-4
    第三章例3-3
    第三章例3-2
    第三章例3-1
    第二章例2-11
    第二章例2-10
    第二章例2-9
    第二章例2-8
  • 原文地址:https://www.cnblogs.com/gattaca/p/6141738.html
Copyright © 2011-2022 走看看