2017-06-18 95 views
-1

我在学习bash的时候,我坚持比较字符串里面的if语句。如果在bash(C风格vs Bash)中比较空字符串

脚本:shiftDemo.sh

1 #!/bin/bash 
    2 
    3 #using shift keyword to shift CLA 
    4 
    5 while true 
    6 do 
    7   if [ "$1" = "" ]  #change this statement wrt below cases 
    8   then 
    9     exit 
10   fi 
11   echo '$1 is now ' "$1" 
12   shift 
13 done 

我使用了以下方法:

1.如果(( “$ 1”= “”))

2.如果[“ $ 1“=”“]

评论:

1A)$ bash shiftDemo.sh first second third

`shiftDemo.sh: line 7: ((: = : syntax error: operand expected (error token is "= ")` 

1b)的$ sh shiftDemo.sh first second third

shiftDemo.sh: 7: shiftDemo.sh: first: not found 
$1 is now first 
shiftDemo.sh: 7: shiftDemo.sh: second: not found 
$1 is now second 
shiftDemo.sh: 7: shiftDemo.sh: third: not found 
$1 is now third 
shiftDemo.sh: 7: shiftDemo.sh: : Permission denied 
$1 is now 
shiftDemo.sh: 12: shift: can't shift that many 

2)在这种情况下,如果语句运行细跟两个壳 &给出正确的输出。

$ bash shiftDemo.sh first second third 
$1 is now first 
$1 is now second 
$1 is now third 

$ sh shiftDemo.sh first second third 
$1 is now first 
$1 is now second 
$1 is now third 

基于上述意见,我的疑惑是:

  1. 什么是错的情况1.如何纠正(我想用C风格的语法在我的脚本)。

  2. 哪些语法是首选,使其既SH & bash shell的工作吗?

+0

重复[**测试bash中的非零长度字符串:\ [-n“$ var”\]或\ [“$ var”\] **](https://stackoverflow.com/questions/3869072/test-for-non-zero-length-string-in-bash-n-var-or-var?noredirect = 1&lq = 1)和[** Unix Bash Shell Script **中的空字符串比较] (https://stackoverflow.com/questions/21407235/null-empty-string-comparision-in-unix-bash-shell-script) –

+1

可能重复[在Unix Bash Shell脚本中的空字符串比较](https: //www.stackoverflow.com/questions/21407235/null-empty-string-comparision-in-unix-bash-shell-script) –

+1

请不要尝试在shell脚本中使用C风格的语法 - 它们是非常不同的语言,如果你尝试在shell中写入C,你将会遇到问题。 –

回答

1

在bash中((...))符号是专门为算术评估(见手册页的算术评估部分)。当执行:

if (("$1" = "")) 

首次,您尝试分配变量first什么也没有,而不是预期的整数值,就像如果你执行:

if ((first =)) 

这没有任何意义,从而出现错误信息。因此,要测试bash变量是否分配了与空字符串不同的值,可以使用test外部命令,即[ ... ]表示法。请输入man test以查看test可以做什么。你可以使用任何的:

if [ -z "$1" ] 
if test -z "$1" 
if [ "$1" = "" ] 
if test "$1" = "" 
if [ "X${1}X" = "XX" ] 
if test "X${1}X" = "XX" 
... 

这是很难说什么((...))做你sh:在大多数系统中,sh是不是原来的Bourne Shell中了。它有时是bash(当被调用为sh时表现不同),或dash或其他。因此,您应该首先检查您的系统上有哪些sh

无论如何,如果test也是一个外部命令你sh(无论您sh是),最好是使用它:通过建设,将具有相同的行为。唯一的区别在于控制结构的语法。