標籤:shell編程 比較操作符 bash編程 字串操作 參數設定
在Linux shell編程中,經常會用到判斷字串是否相等,可用於判斷字串是否相等的操作符有‘-eq’(相等), ‘-ne’(不等於), ‘-lt’(小於), ‘-le’(小於或等於), ‘-gt’(大於)或‘-ge’(大於或等於),以及=,==,!=,<,>。
在bash指南中,字母操作符和符號操作符的兩端的參數英語運算式不相同,符號操作符用的是string,字母操作符用的是arg。
# http://www.gnu.org/software/bash/manual/bashref.html
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<string2
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 [email protected] filename" && exit 1
修改為
[[ "$1" == "" ]] && echo "delete all spaces and comments of specialized file, using with [email protected] filename" && exit 1
就不再提示了。
附帶一個實用小指令碼,用途:grep掉空格和注釋符(#),簡單實用。
#!/bin/bash # delete all spaces and comments of specialized file, using with [email protected] filename [[ "$1" == "" ] && echo "delete all spaces and comments of specialized file, using with [email protected] filename" && exit 1 grep -v \# $1 | grep -v ^$
添加到作業系統中:
cat > delsc.sh << eof #!/bin/bash # delete all spaces and comments of specialized file, using with [email protected] filename [[ "\$1" -== "" ]] && echo "delete all spaces and comments of specialized file, using with \[email protected] 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
本文出自 “通訊,我的最愛” 部落格,請務必保留此出處http://dgd2010.blog.51cto.com/1539422/1542048