我在学习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.如何纠正(我想用C风格的语法在我的脚本)。
哪些语法是首选,使其既SH & bash shell的工作吗?
重复[**测试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) –
可能重复[在Unix Bash Shell脚本中的空字符串比较](https: //www.stackoverflow.com/questions/21407235/null-empty-string-comparision-in-unix-bash-shell-script) –
请不要尝试在shell脚本中使用C风格的语法 - 它们是非常不同的语言,如果你尝试在shell中写入C,你将会遇到问题。 –