How can I run/source a shell script (bash if that matters) and have the output include the commands within the script? I'd like to redirect the output to a file as in

$ ./my_script > output.txt

and have the output.txt file contain the commands from the script as if I had entered its contents into a terminal interactively and then copy-pasted the terminal window's contents into a file.

Bonus points for solutions that make the commands visually different from the output lines, as in a terminal with the preceding $.

  • @steeldriver The question is different: I don't want to enter those commands interactively, I want to run a script non-interactively but have the output look as if I had entered all script commands manually.
    – FriendFX
    Mar 16, 2020 at 22:44
  • ah OK I see ... Mar 16, 2020 at 22:54

1 Answer 1


In your script add the following line before any commands (this writes each command to stderror before executing it):

set -x

then start your script:

./my_script > output.txt 2>&1

  • +1, I knew it would be something simple like this... strange I couldn't find it easily.
    – FriendFX
    Mar 16, 2020 at 23:08

You must log in to answer this question.

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