Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a log of output using redirect

Tags:

bash

shell

I'm creating my first script using "The Advanced Bash Scripting Guide".

One of the exercises asks for a script that, once run, saves the output to a log file.

I've managed to create my first basic script but am having trouble with this last part. The script must contain the code to create the logfile but I can only do it separately in the shell.

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

Here's 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 have to do (In as simple English as possible) to have the script create the output file by itself, rather than having to do separately in the shell once run?

like image 937
Doug Fir Avatar asked Jan 14 '23 05:01

Doug Fir


1 Answers

usually enough enclose the parts to ( ), like:

#!/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
like image 104
jm666 Avatar answered Jan 20 '23 21:01

jm666