简体   繁体   中英

Bash Redirecting Output From Multiple Functions to A File

I am trying to make a script that will redirect some output from a couple of functions to a file. Here is what my code looks like.

#!/bin/bash

touch /var/log/test.log
results=/var/log/test.log

outputFormat()
{
    echo "This is outputFormat" >> results
}

outputParseFull()
{

    echo "This is outputParseFull" >> results
    outputFormat;
}

outputParseFull;

After running this, /var/log/test.log is created but the file itself is blank. I want the file to contain the following

This is outputParseFull

This is outputFormat

One line must be from each function. What am I doing wrong here?

You're writing to a file named results , not using the filename in the variable $results .

echo "This is outputParseFulll" >> results

should be

echo "This is outputParseFulll" >> $results

1.), when using an variable, you should to use $results instead of the plain results .

2.), you can short your script, redirecting the output from the function, like:

results="./file"
touch "$results"

outputFormat() {
    echo "This is outputFormat"
}

outputParseFull() {
    echo "This is outputParseFull"
    outputFormat;
}

outputParseFull >"$results"

3.) Always quote filenames, like "$filename" . (because, they can contain spaces)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM