2016-06-13 34 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