1

I am trying to save all output of a collection to separate files. For example one function will be like:

function kernel_info(){
   echo "Kernel version: $(uname -v)"
}

I want to write this output to file which will have kernel_info as it name. Similarly I will create other functions to gather other information like hostname, etc. How can I write a function which I can call every time I want to save the information to a file on disk? Thanks

4 Answers 4

1

Use tee.

kernel_info () {
   { printf 'Kernel version: '
     uname -v
   } | tee -a /path/to/kernel_info
}

This function will write the combined output of printf and uname to the given file, and continue to write the same to standard output.

The -a option makes tee append to the file.

If you want to parameterize the function, you can.

kernel_info () {
   local fname
   fname=${1:-/default/path/to/kernel_info}
   { printf 'Kernel version: '
     uname -v
   } | tee -a "$fname"
}

kernel_info  # Writes to /default/path/to/kernel_info
kernel_info /var/log/kernel_info  # Write to an alternate file
Sign up to request clarification or add additional context in comments.

3 Comments

The second one leaks fname, shouldn't that be local?
It can be. It's not often I'm too concerned about such leaks, so I don't immediately jump to using local.
(local also as the "distinction" of being the only non-POSIX part of the answer.)
0

You can automate the naming via perusing How to determine function name from inside a function - and simply

... | tee "${FUNCNAME}.log"

within the function where you'd like to log to a specifically-named output file.

1 Comment

the tee function works well. I am trying to zip it at the same time but not able to. |tee "$directory_name""_${FUNCNAME}.txt" > /dev/null How can I use tee in conjunction with tar in the above line?
0

Define a list of functions to loop over then call them and then redirect the result into a file,

> replace, >> append

#!/bin/bash

function local_hostname() {
    echo "Hostname: $(hostname)"
}

function kernel_info() {
    echo "Kernel version: $(uname -v)"
}

function write_to_file() {
    > file.txt

    funcs=(
        local_hostname
        kernel_info
    )
    for func in ${funcs[*]}
    do
       $func >> file.txt
    done
}

write_to_file

Comments

0

You can keep it simple...

$: tst() { date ; } >>log
$: ls -l log
ls: cannot access 'log': No such file or directory
$: tst
$: cat log
Wed, Jun 17, 2020  8:12:10 AM
$: tst
$: cat log
Wed, Jun 17, 2020  8:12:10 AM
Wed, Jun 17, 2020  8:12:17 AM

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.