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

oguz ismail
  • 1
  • 16
  • 47
  • 69
Rookie
  • 13
  • 4

4 Answers4

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
chepner
  • 497,756
  • 71
  • 530
  • 681
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.

FrankH.
  • 17,675
  • 3
  • 44
  • 63
  • 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? – Rookie Jun 18 '20 at 13:47
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
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
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
Paul Hodges
  • 13,382
  • 1
  • 17
  • 36