2015-11-13 85 views
1

我在shell腳本中有以下代碼。這一切工作正常。簡化bash代碼

#!/bin/bash 

baseDirPath = '/stackoverflow/question' 
newDir = '/stackoverflow/question/answers' 


# first check some business condition 
if [[ some condition here ]] 
then 
    # check if base Directory path already exit 
    if [ -d $baseDirPath ];then 

     # check if new Directory exits or not, if not create one 
     if [ ! -d $newDir ];then 

      mkdir $newDir 
      if [ $? -ne 0 ] ; then 
      echo "error occurred while creating directory " 
      fi 
     fi 
    else 
     exit 1; 
    fi 
fi 

這是非常混亂,不是很乾淨的代碼,我覺得。 我對編程非常陌生,所以不確定它是如何清潔的。

我很好奇,如果它可以變得更簡單或有一些其他方式來做到這一點。

(完整的shell腳本並不如上圖所示,只是複雜的if-else部分所示)。

+0

只是一個友好僅供參考,shell腳本不一定是Perl腳本。這個特定的shell腳本是bash,如頂部的shebang('#!')所示。 Perl是一種獨立的編程語言,看起來與bash腳本類似,但功能更強大,功能更強大。 – mwp

+0

正如@mwp所說,這不是Perl。我修改了標題以反映這一點,並做了一些其他修改來修復代碼格式和語法。如果你不喜歡我所做的,請隨意[編輯](http://stackoverflow.com/posts/33699153/edit)或回滾(和編輯頁面上的選項)。 – PTBNL

+2

你的意思是'baseDirPath ='/ stackoverflow/question''沒有空格嗎?如果等號周圍有空白,分配不起作用。 –

回答

4
#!/bin/bash 

die(){ >&2 printf '%s\n' "[email protected]"; exit 1; } 

#Can't have spaces here 
baseDirPath='/stackoverflow/question' 
newDir='/stackoverflow/question/answers' 


# first check some business condition 
if [ some condition here ]; then 
    # check if base Directory path already exit 
    mkdir -p "$newDir" || die 'error occured while creating directory' 
fi 

這會稍微改變語義 - 它退出如果newDirs創造不管是什麼原因失敗 - baseDirPath不是目錄或baseDirPath是不能創建的目錄和newDir

你也可以擺脫那個錯誤信息。 mkdir就已經給你在stderr上一個錯誤,如果它由於某種原因失敗:

mkdir -p "$newDir" || exit 1 

如果你的大多數命令應該像這樣工作(即成功或搞垮整個腳本),那麼你很可能最好設置set -e(〜退出時具有非零狀態的命令返回),然後就做:

mkdir -p "$newDir" 
1

這可以很徹底簡化:

#!/bin/bash 
baseDirPath='/stackoverflow/question' 
newDir='/stackoverflow/question/answers' 

# first check some business condition 
if [[ some condition here ]]; then 
    if ! mkdir -p "${newDir}"; then 
     echo "Unable to create directory ${newDir}. Aborting." 
     exit 1 
    fi 
    # Proceed as normal 
fi 

如果你真的需要爲baseDirPath存在,那麼肯定可以添加一個條件:

if [[ ! -d "${baseDirPath}" ]] || ! mkdir -p "${newDir}"; then 
+1

爲什麼使用大括號?這些擴展都沒有被參數化,並且在任何這些情況下都沒有歧義變量名。 –

+0

我經常使用花括號來消除變量名的歧義,這也意味着當將變量嵌入到其他文本(例如'$ {varname} _ext',它在語義上不同於'$ varname_ext')時,我不需要做任何事情。由於始終使用捲髮是規則評估者而非例外情況,因此它使語法更加一致。這也是我總是使用'[[]]'對的原因,即使'[]'在技術上是可行的。 – DopeGhoti