2011-04-02 35 views
2

好,我不能讓這出於某種原因提前容易BASH的if else

if /etc/mysql/my.cfn exist 
    then goto end; 
else bash install.sh; 

end exit;; 

謝謝, 喬

+1

應該是'在/ etc/mysql /下my.cnf',我想。 – 0xC0000022L 2011-04-02 19:51:24

回答

8

這裏有一個相對直譯:

if [ -e /etc/mysql/my.cfn ]; then 
    exit # Note: bash does not have a goto command 
else 
    bash install.sh 
fi 

或者,消除那麼無關緊要的條件,和反轉測試:

if [ ! -e /etc/mysql/my.cfn ]; then 
    bash install.sh 
fi 
10

檢查不存在的,如果真正運行install.sh

[[ ! -e /etc/mysql/my.cfn ]] && bash install.sh 
+0

+1,喜歡簡潔的形式,太... – 0xC0000022L 2011-04-02 19:50:48

+0

+1的風格... – lecodesportif 2011-04-02 23:09:02

+0

由於某種原因,即使文件中存在這種沒有工作,仍然跑腳本。 – jmituzas 2011-04-02 23:57:26

1

(一)正確的語法是:

if [[ expression ]]; then 
    command 
else 
    command 
fi 

傳統的風格將是:

if test -f filename; then 
    command 
fi 
4

你四行猛砸的一行:

[[ -e /etc/mysql/my.cfn ]] && exit || bash install.sh 

您是不是要找我。 CNF

+2

更少的代碼只有更好,當你正在做的每行一兩件事。 – Johnsyweb 2011-04-02 22:26:02

+0

不完整'[[..]] && .. || ..測試結構按定義做至少兩件事情?如果它簡短易讀,則可以在一行上完成。 – lecodesportif 2011-04-02 23:03:23

+1

的確如此定義,這是我的一點做多件事情。它使代碼難以維護。 – Johnsyweb 2011-04-03 03:10:07

5

在不帶任何參數猛砸:命令是一個空操作,所以你可以,如果你需要做什麼使用在if體。

if something; then 
    : 
else 
    do something else 
fi 

當然,你通常需要寫爲:

if ! something; then 
    do something else 
fi 

something || do something else