2016-12-02 80 views
0

我在寫這個問題,因爲我不熟悉sh腳本,但我知道以下行在/ bin/bash中工作,但我需要使用/ bin/sh。下面是代碼:sh腳本在一個函數中訪問全局變量

#!/bin/sh 

trythis=1 

test() 
{ 
    ((trythis++)) 
    echo $trythis 
} 

test 

我希望2作爲輸出,而是我得到以下錯誤:

./test: 7: ./test: trythis++: not found 
1 
+1

在頂部使用'#!/ bin/bash'代替'#!/ bin/sh' – anubhava

+2

問題出在Bash語法' trythis ++))',而不是變量本身。正如@anubhava指出的那樣,如果你想使用bashisms,請使用Bash。 – fedorqui

回答

1

而不是

((trythis++)) 

使用本:

trythis=`expr $trythis + 1` 

expr(1)是接收參數1,+,1的外部程序進行計算並打印2,由於反引號而被分配到trythis。 (請參閱man expr,嘗試在控制檯上輸入類似expr 1 + 2的東西。)

+0

嘿,工作!你能鏈接或解釋我爲什麼這個工程? – daemoner119

+0

更新了答案。 –

+1

不需要'expr'; 'trythis = $((trythis + 1))'將在任何POSIX兼容的shell中工作。 – chepner