0

I am at the beginning with bash scripts, I would like to know if I can put a command at the beginning in which after each: echo "123" to appear >> filename

I have a lot of lines with echo "etc" and I want to move all the results from echo to a certain file.

I hope there is someone who knows how much I need.

I searched for tutorials but I didn't find anything and I don't know what to do.

I will be very grateful if you help me! <3 peace

Z4-tier
  • 7,287
  • 3
  • 26
  • 42
  • 1
    you might want to use `set -vx` although I don't really understand your question... – Z4-tier Nov 16 '20 at 23:28
  • In general, it's always a bad idea to use `>> anywhere` over and over -- doing so, your code re-opens the output file for every invocation. – Charles Duffy Nov 16 '20 at 23:40
  • If you just want to redirect **all** stdout, you can just put `exec >outfile` at the top of your script (`>` instead of `>>` because it's only opening it once, so you can afford to truncate). – Charles Duffy Nov 16 '20 at 23:40
  • If you _only_ want to redirect stdout of your `echo`s, then you should probably wrap `echo` in a function that performs the redirection you want (albeit to a pre-opened file for better performance). – Charles Duffy Nov 16 '20 at 23:41
  • ...so that might be something like `exec {log_fd}>filename` at the top of your script, and then `log() { echo "$@" >&"$log_fd"; }` to create a `log` command that acts like `echo` except that it writes to your `filename` instead of stdout. Then instead of `echo "etc"` you use `log "etc"` and there you are. – Charles Duffy Nov 16 '20 at 23:42
  • ...but these are all comments instead of answers because the question isn't clear enough for me to be sure the above is what you're asking how to do. Please try to be as explicit as possible. – Charles Duffy Nov 16 '20 at 23:42
  • @CharlesDuffy and if I put `` exec> outfile`` at the beginning all `` echo "" etc .... "` `will it go in` `outfile``? I just want the result to go like` `echo "" elephant "" `` in the outfile to be elephant – HelpPlease52 Nov 16 '20 at 23:45
  • Yes, all `echo`s will go to `outfile`. The caveat is that it doesn't just change where `echo` goes, but where _everything_ that writes to stdout goes (but not stderr, which will retain its original destination). **Is that what you're asking how to do?** Please answer that question, yes or no. – Charles Duffy Nov 16 '20 at 23:46
  • Yes, thanks you very much. – HelpPlease52 Nov 16 '20 at 23:48

0 Answers0