Let's say I had a loop in terminal that created a set of directories, performed a set of tasks, and I wanted for each command family of commands to be written to log files in a new directory. This can be achieved in a few ways (using echo/going with python), but I was wondering is there any easy way to easily pass a command at the front of my loop that just will automatically create a log file in the new directory of the commands the loop runs. EDIT: By a log file here I mean to only collect the final commands that are passed to the terminal.

Part of the motivation for this is that I'm going to be randomly generating fluctuations in the parameters I pass in my commands, and it'd be much to just be like "flag the following commands in this loop for logging" vs having to assign variable values and then echo them. Learning if there is a sort of "log" command would be helpful in many other scenarios, so I'd prefer answers to that effect.

1 Answer 1


Do the important commands in a group, and redirect the output from the group:

for dir in dir1 dir2 ...; do
    logfile="$dir"/log.log       # or whatever name you want
         : create a set of directories
         : perform a set of tasks
    } > "$logfile"

If you want to want the output on the terminal as well, change the redirection to a pipe to tee

    } | tee "$logfile"
  • here the only thing output is my actual commands, and not the output from the command, right?
    – user507974
    Nov 9, 2015 at 22:03
  • no, the commands will run, and the output will be logged. Nov 10, 2015 at 4:29
  • Is there anyway to do this the other way around, where the only thing logged are the commands
    – user507974
    Nov 12, 2015 at 19:52
  • This is because a step of this loop runs a simulation that creates 200k+ lines of text but saves its own file with the useful information.
    – user507974
    Nov 12, 2015 at 19:58
  • 1
    I have a function I sometimes use for debugging: echocmd () { echo "$@"; "$@"; } that prints a command then executes it. You could adapt that. Nov 12, 2015 at 20:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.