2016-06-13 32 views
-2

我有一個帶參數文件的函數。我想逐行閱讀。從函數中的參數文件逐行讀取

條件

如果行<?bash?>之間,然後我做bash -c '$line'否則我顯示行。

這裏我的文件(文件):

<html><head></head><body><p>Hello 
<?bash 
echo "world !" 
?> 
</p></body></html> 

這裏我bash腳本(bashtml):

#!/bin/bash 

function generation() 
{ 
    while read line 
    do 
    if [ $line = '<?bash' ] 
    then 
     while [ $line != '?>' ] 
     do 
     bash -c '$line' 
     done 
    else 
    echo $line 
    fi 
    done 
} 

generation $file 

我執行這個腳本:

./bashhtml 

我我是Bash腳本的新手'm迷失

+2

我沒有看到問題。 –

+2

從Biffens的評論中可以看出,即使您正確地聲明並調用了函數,它仍然無法正常工作,因爲在匹配'<?bash'之後,如果您沒有獲得新行,直到您離開if語句。 – 123

+1

...除了事實上你並沒有在任何地方讀取文件 – cdarke

回答

1

我認爲這是你的意思。但是,此代碼非常危險!插入到這些bash標籤中的任何命令都將在您的用戶標識下執行。它可能會更改密碼,刪除所有文件,讀取或更改數據等等。不要這樣做!

#!/bin/bash 

function generation 
{ 
    # If you don't use local (or declare) then variables are global 
    local file="$1"    # Parameter passed to function, in a local variable 
    local start=False   # A flag to indicate tags 
    local line 

    while read -r line 
    do 
    if [[ $line == '<?bash' ]] 
    then 
     start=True 
    elif [[ $line == '?>' ]] 
    then 
     start=False 
    elif "$start" 
    then 
     bash -c "$line"  # Double quotes needed here 
    else 
     echo "$line" 
    fi 
    done < "$file"    # Notice how the filename is redirected into read 
} 

infile="$1"     # This gets the filename from the command-line 
generation "$infile"   # This calls the function 
+0

我重寫了你的腳本,現在我明白瞭如何實現我的功能。謝謝:) – XZKS

+1

@XZKS:請注意,我使用雙'[[''而不是單。在這種情況下,它們表示變量值'$ line'不需要引用,但還有其他差異。如果您不確定任何事情,請隨時提出有關此代碼的進一步問題。 – cdarke