linux eq ==,Linux shell中比较操作符“==”与“-eq”对比

本文介绍了在Linux shell编程中如何使用不同操作符判断字符串相等或不等,包括'='、'=='、'!='以及'eq'、'ne'等。在实际应用中,使用字母操作符可能会导致错误提示。通过示例脚本展示了如何修正这一问题,该脚本用于删除文件中的空格和注释。修正后的脚本避免了错误提示,并提供了实用的文件处理功能。
摘要由CSDN通过智能技术生成

在Linux shell编程中,经常会用到判断字符串是否相等,可用于判断字符串是否相等的操作符有‘-eq’(相等), ‘-ne’(不等于), ‘-lt’(小于), ‘-le’(小于或等于), ‘-gt’(大于)或‘-ge’(大于或等于),以及=,==,!=,。

在bash指南中,字母操作符和符号操作符的两端的参数英语表达式不相同,符号操作符用的是string,字母操作符用的是arg。

# http://www.gnu.org/software/bash/manual/bashref.html

string1==string2

string1=string2

True if the strings are equal. ‘=’ should be used with the test command for POSIX conformance.

string1!=string2

True if the strings are not equal.

string1

True ifstring1sorts beforestring2lexicographically.

string1>string2

True ifstring1sorts afterstring2lexicographically.

arg1OParg2

OP is one of ‘-eq’, ‘-ne’, ‘-lt’, ‘-le’, ‘-gt’, or ‘-ge’. These arithmetic binary operators return true ifarg1is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal toarg2, respectively.Arg1andarg2may be positive or negative integers.

在实际编程中发现,当用字母操作符,虽然效果与符号操作符相同,但会产生一个错误提示“[[: arg2: syntax error: operand expected (error token is "arg2")”。

如原文为

[[ "$1" -eq "" ]] && echo "delete all spaces and comments of specialized file, using with $@ filename" && exit 1

修改为

[[ "$1" == "" ]] && echo "delete all spaces and comments of specialized file, using with $@ filename" && exit 1

就不再提示了。

附带一个实用小脚本,用途:grep掉空格和注释符(#),简单实用。

#!/bin/bash

# delete all spaces and comments of specialized file, using with $@ filename

[[ "$1" == "" ] && echo "delete all spaces and comments of specialized file, using with $@ filename" && exit 1

grep -v \# $1 | grep -v ^$

添加到操作系统中:

cat > delsc.sh <

#!/bin/bash

# delete all spaces and comments of specialized file, using with $@ filename

[[ "\$1" -== "" ]] && echo "delete all spaces and comments of specialized file, using with \$@ filename" && exit 1

grep -v \# \$1 | grep -v ^$

eof

chmod +x ./delsc.sh

\mv delsc.sh /usr/local/bin/delsc

which delsc

cat /usr/local/bin/delsc

用法:

delsc filename

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值