Shell output redirection inside a function

本秂侑毒 提交于 2019-12-25 04:51:49

问题


function grabSourceFile
{
    cd /tmp/lmpsource
    wget $1 >  $LOG
    baseName=$(basename $1)
    tar -xvf $baseName > $LOG
    cd $baseName
}

When I call this function The captured output is not going to the log file. The output redirection works fine until I call the function. The $LOG variable is set at the top of the file. I tried echoing statements and they would not print. I am guessing the function captures the output itself? If so how do push the output to the file instead of the console. (The wget above prints to console, while an echo inside the function does nothing.)


回答1:


As mentioned earlier, you are writing to the same logfile twice. Your function is logging the output of 'wget' and is then overwriting that output later on, with the tar command.

Myself, I like to log outside of functions. This will reduce the chance that your logfile gets clobbered. It also keeps the function code neat and tidy.

function grabSourceFile
{
        cd /tmp/lmpsource
        wget $1
        baseName=$(basename $1)
        tar -xvf $baseName
        cd $baseName
} >> $LOG

Or just do:

grabSourceFile >> $LOG



回答2:


Redirection works the same inside and outside of functions.

Your problem is likely that you want a double greater than sign rather than a single greater than sign. I.e. wget $1 >> $LOG. The redirection on your tar command truncates the output from wget.




回答3:


I found the problem. It was with wget. wget has an option specifically for logging as I guess it can't have it's output redirected using the > (something with curses.) My working function ended up being:

function grabSourceFile
{
        cd /tmp/lmpsource
        wget -a /tmp/lamps_install.log $1
        baseName=$(basename $1)
        tar -xvf $baseName >> $LOG
        cd $baseName
}


来源:https://stackoverflow.com/questions/2952809/shell-output-redirection-inside-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!