Creating an output log using redirection

I create my first script using the "Advanced Bash Scripting Guide".

In one of the exercises, a script is proposed that, after starting, saves the output to a log file.

I managed to create the first base script, but I had problems with this last part. The script must contain the code to create the log file, but I can do it separately in the shell.

The file is called myFirstShellScript.txt. When i run. /myFirstShellScript.txt, the script starts. After running the script, if I type ./myFirstShellScript.txt > myFirstShellScriptLog in the shell, a new file is created with the output. Now I tried to add this line to the script, but the file that was output was empty.

Here is my first script, please don't laugh.

 #! /bin/bash # show todays date and time echo "Todays date is $(date +%j)." # Show who is currently logged into the system echo $(who) # show system uptime echo $(uptime) # log output in separate file using redirect exit 

What do I need to do (in English as simple as possible) for the script to create the output file by itself, instead of doing it separately in the shell after starting?

+4
source share
2 answers

usually it’s enough to enclose the parts in ( ) , for example:

 #!/bin/bash ( # show todays date and time echo "Todays date is $(date +%j)." # Show who is currently logged into the system echo $(who) # show system uptime echo $(uptime) ) > myFirstShellScriptLog 
+5
source

You can use the built-in exec command to redirect script output to a file from a script:

 #! /bin/bash # Save output to "log.txt" exec > log.txt # show todays date and time echo "Todays date is $(date +%j)." ... 
+4
source

Source: https://habr.com/ru/post/1483851/


All Articles