shell練習題2

需求以下:shell

寫一個shell腳本,檢查指定的shell腳本是否有語法錯誤,如有錯誤,首先顯示錯誤信息,而後提示用戶輸入q或Q退出腳本,vim

輸入其餘內容則直接用vim打開該shell腳本。bash

參考解答以下code

  • 方法1
#!/bin/bash

cmd="/bin/bash"
ed="/usr/bin/vim"

if [ $# -ne 1 ];then
    echo "USAGE:$0 script_name"
    exit 1
fi

$cmd -n $1
if [ $? -ne 0 ];then
    read -p "Please enter Q/q to exit, or other to edit it by vim."
    if [ "$REPLY" = "q" -o "$REPLY" = "Q" ];then
        exit 0
    else
        $ed $1
    fi
else
    echo "The scipt is OK."
fi
  • 方法2
#!/bin/bash

cmd="/bin/bash"
ed="/usr/bin/vim"

if [ $# -ne 1 ];then
    echo "USAGE:$0 script_name"
    exit 1
fi

$cmd -n $1 2>/tmp/err
if [ $? -eq 0 ];then
    echo "The script is OK."
else
    cat /tmp/err
    read -p "Please enter Q/q to exit, or other to edit it by vim." n
    if [ -z $n ];then
        $ed $1
        exit
    fi
    if [ "$n" = "q" -o "$n" = "Q" ];then
        exit
    else
        $ed $1
        exit
    fi
fi

注意: bash -n選項只檢測語法錯誤。ip

相關文章
相關標籤/搜索