0

I'm trying to run a command and log only the command to a file. I've tried using exec 4>test|command >&4|exec 4>&- but doesnt' work. If I run the commands separately it works but only records the output of the command, the same with command | tee -a test. I also found this: command|& ts |tee -a test but I don't have admin rights so I can't install anything. Also I don't want to write a script or save the command history or the output, preferably I just want a one liner to record the command to a file and then execute it normally. This are some related questions: https://stackoverflow.com/questions/70677322/in-linux-how-to-save-only-the-command-into-file-without-output Record commands only to file

3
  • 1
    Does "logging the command" differ from "record the output of the command" somehow?
    – Kusalananda
    Sep 25 at 17:04
  • If your goal is to provide a secure record of commands a user executes, that's what auditing is for. Simply writing to a log file that the user has generic write permission to is completely unsuitable for creating a secure history of what the user does - the user can modify it any time they want. Sep 25 at 17:13
  • The first question link is what I wanted to do, I don't want the output nor an audit, just the command. It's more like trying a new command and thinking it could be helpful for a future script or something and appending it to a file on the fly, that's all.
    – dsaizt
    Sep 25 at 22:22

1 Answer 1

0

If it's in a shell scripting environment, you could make a function like so, which executes the given arguments:

log_and_execute_command() {
    printf '%(%FT%T%z)T\t%s\n' -1 "$*" >> my_logging_file
    "$@"
}

If we don't need to record timestamps, it gets a bit easier. This one uses the fact that if you pass commands in the standard input to the shell, it executes them:

printf '%s' 'my_command' | tee -a my_logging_file | sh

If you want to pipe something into ts but don't have it, a shell script like this can be used as a similar alternative:

#!/bin/bash
while read -r line; do
    printf '%(%FT%T%z)T\t%s\n' -1 "$line"
done
1
  • 1
    Second option was the one I was lookin for, I only added \n after %s
    – dsaizt
    Sep 25 at 22:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .