【问题标题】:CASE is behaving different in Debug and normal mode [duplicate]CASE 在调试和正常模式下的行为不同[重复]
【发布时间】:2016-10-20 07:44:09
【问题描述】:

我编写了一个脚本,其中“CASE”部分识别输入的字节/字符是 Lower、Upper、digit 还是某些特殊字符。该程序运行良好,但奇怪的是;当我输入字母“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

【问题讨论】:

  • 脚本在这两种情况下都会输出Lower case alphabet。也许您实际上正在调用不同的脚本,或者它只是这篇文章中的一个错字:sh -x ./scrip "A"? (你的意思是sh -x ./script "A"?)
  • 在这两种情况下添加 LC_ALL=CLC_ALL=C ./script "A"sh -x ./scrip "A" 以消除 locale 问题。
  • 此外,如果没有 shebang 行,则在没有 sh 的情况下调用脚本时,不清楚脚本在哪个 shell 中运行,sh 也不清楚,因为它可能是 bash,@ 987654336@,或其他取决于您的发行版的口味。
  • 因为这都是关于区分大小写的:该语句称为case 而不是CASE。 (如果不能,shell 应该如何区分大小写字母?)
  • 感谢大家的有用回复。我添加了(#!/bin/sh)并且它有效。现在脚本将仅由 /bin/sh 执行,但是这个环境变量的含义是什么?我的意思是“LC_COLLATE”,分配“C”有什么区别?

标签: bash shell


【解决方案1】:

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

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

  • bash(以./script.sh 运行时恰好执行脚本)可以将A 匹配到特定语言环境的[a-z]

解决方法是同时指定 shebang 和整理顺序:

#!/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

【讨论】:

  • 谢谢。有效。但我不明白 LC_COLLATE="C" 的含义。它的目的是什么?
  • @NoumanTajik Stack Overflow 表示“谢谢”的方式是upvote。如果帖子回答了您的问题,您应该(也)接受它。
  • LC_COLLATE 设置排序顺序(在给定的locale 内,字符如何排序、被视为相等……)。 CPOSIX locale,它为“计算机而不是人类”进行整理
  • 我尝试了“up-vote”,但堆栈溢出显示“感谢您的反馈,声望低于 15 的人的投票已记录,但不要更改公开显示的分数” .我最近加入了堆栈溢出,也许他们不考虑新手的投票:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-25
  • 2011-06-14
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 2016-05-12
相关资源
最近更新 更多