user26767
user26767

Reputation: 331

Is it possible to direct the executed command in a script with bash?

I have a script that executes a program and direct the output to a log file.

./a.out --option 1  > log.txt
./a.out --option 2 >> log.txt
...

I would like to direct the executed command lines ( "./a.out --option 1 ", "./a.out --option 1 ",...) to the same log file so that I could distinguish which output is for which command. Is it possible? I could add "echo command" but it doesn't seem a good way to do it since I have to write the same string twice and possibly make a mistake.

It seems trivial but I could not find on Google or a similar quesition:( so please let me ask here. Thanks in advance!

Upvotes: 2

Views: 33

Answers (2)

Denio Mariz
Denio Mariz

Reputation: 1195

You can put commands in a sequence, like this:

( cmd1 ; cmd2 ; cmdn ) > file

Upvotes: 0

melpomene
melpomene

Reputation: 85767

You could create a function:

my_command() {
    { echo "Option $1"; ./a.out --option "$1"; } >> log.txt
}

my_command 1
my_command 2

If you want to store the whole command line, you could use a variable:

my_command() {
    local cmd="./a.out --option $1"
    { echo "$cmd"; $cmd; } >> log.txt
}

my_command 1
my_command 2

Upvotes: 2

Related Questions