我在學習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,你將會遇到問題。 –