CASE在调试和普通模式下表现不同

时间:2016-10-20 07:44:09

标签: bash shell

我写了一个脚本,其中“CASE”部分标识输入的字节/字符是下,上,数字还是某些特殊字符。程序运行正常,但奇怪的是;当我输入字母“A”,然后运行

sh -x ./scrip "A"

输出

+ [ 1 -ne 1 ]
+ char=A
+ wc -c
+ echo A
+ NumOfChars=2
+ [ 2 -gt 2 ]
+ echo  Arguments are correct in numbers 
 Arguments are correct in numbers 
+ echo Upper case alphabet
Upper case alphabet

输出正确(即执行[A-Z]的情况

但是当我执行该程序是正常的时尚,即

./script "A"

输出

Lower case alphabet

执行CASE [a-z],为什么?

脚本如下

if [ "$#" -ne 1 ]; then
    echo "Number of arguments are wrong"
    exit 1;

else
    char="$1"
    NumOfChars=$(echo "$char" | wc -c)
    if [ "$NumOfChars" -gt 2 ]; then
        echo "Number of characters are greater then one"
        exit 2;
    else
        echo " Arguments are correct in numbers ";
    fi
fi
case "$char"
in

[a-z] ) echo "Lower case alphabet";;
[A-Z] ) echo "Upper case alphabet";;
[0-9] ) echo "Digit";;
* )     echo "Non AlphaNumeric characters/byte";;
esac

1 个答案:

答案 0 :(得分:0)

所以你被两个不同的问题所困扰:

  • 由于缺少shebang,当使用./script.sh resp运行时,不同的 shell实现将执行/可执行脚本。 bash

  • ./script.sh(在A运行时恰好执行脚本)可以将[a-z]与特定区域设置的#!/bin/sh export LC_COLLATE="C" # the rest of the script is unchanged. if [ "$#" -ne 1 ]; then echo "Number of arguments are wrong" exit 1; else char="$1" NumOfChars=$(echo "$char" | wc -c) if [ "$NumOfChars" -gt 2 ]; then echo "Number of characters are greater then one" exit 2; else echo " Arguments are correct in numbers "; fi fi case "$char" in [a-z] ) echo "Lower case alphabet";; [A-Z] ) echo "Upper case alphabet";; [0-9] ) echo "Digit";; * ) echo "Non AlphaNumeric characters/byte";; esac 匹配。

修复是指定shebang和整理顺序:

for(k=begin;k<=end;k++){
        ptr[k] = str[k];
    }