2

Here's the general command logging function I wrote:

function exec_cmd() {
  {
    echo "$(date '+%Y-%m-%d %H:%M:%S')" "$1"
    $1
  } >>./cmd.log
}

When I call this function with exec_cmd "modprobe -r toa || true", I got an error "modprobe: FATAL: Module || not found."

Running the same command without the wrapper exec_cmd works as expected.

The whole script is running in strict mode. The || were included because only the error from this command can be ignored.

Blaise Wang
  • 556
  • 5
  • 17

2 Answers2

1

Bash has builtin support for printing commands as they are executed, namely the -x flag. From man bash:

-x Print commands and their arguments as they are executed.

So you can revise your script to call set -x as the first command, then every command after that is printed in the sequence they are called.

#!/bin/bin/env bash
set -x

modprobe -r toa || true
Esa Lindqvist
  • 311
  • 2
  • 6
0

I would write the function like this :

#!/usr/bin/env bash
  
function exec_cmd() {
  {
    printf "$(date '+%Y-%m-%d %H:%M:%S') %s\n" "$*"
    "$@"
  } >> ./cmd.log
}

exec_cmd modprobe -r toa || true
Philippe
  • 20,025
  • 2
  • 23
  • 32
  • Thanks. I am also writing an almost identical answer after reading @user202729's comment. I will accept your answer since you posted the first answer. – Blaise Wang Feb 22 '21 at 10:36