Bash script: Using “script” command from a bash script for logging a session

前端 未结 5 1540
谎友^
谎友^ 2020-12-05 05:03

I am trying to use script command for logging a bash session.

The script command is executed from withing a bash script but as soon as it i

5条回答
  •  醉话见心
    2020-12-05 05:35

    Your shell script did not terminate. It is still running. You are getting a prompt because script is spawning a new shell. the prompt you see is the prompt from the spawned shell.

    The normal use case for script is something like this:

    1. start script. this spawns a new shell.
    2. do commands in the new shell.
    3. exit the shell and drop to previous shell
    4. examine the logfile created by script

    So basically script is working as expected. You will have to find another way to achieve what you want.

    You can log the execution of your script like this:

    #! /bin/bash
    exec > logfile 2>&1
    set -x
    FOO=BAR
    echo $FOO
    

    Explanation:

    • exec > logfile 2>&1 redirects stdout and stderr to logfile
    • set -x makes bash print every command before executing it

    Example:

    $ ./foo.sh
      # (no output here because everything goes to logfile)
    $ cat logfile 
    + FOO=BAR
    + echo BAR
    BAR
    

    Disadvantage of this method is that the script prints no output for humans to see. Everything goes to the logfile.

    Alternatively you can do it like this:

    #! /bin/bash
    # nothing special here
    FOO=BAR
    echo $FOO
    

    Then execute like this:

    $ script -c "bash -x foo.sh"
    Script started, file is typescript
    + FOO=BAR
    + echo BAR
    BAR
    Script done, file is typescript
    

    now output is directly visible and also saved to logfile (default name of logfile is typescript)

    $ cat typescript 
    Script started on Mi 18 Mai 2011 01:05:29 CEST
    + FOO=BAR
    + echo BAR
    BAR
    
    Script done on Mi 18 Mai 2011 01:05:29 CEST
    

提交回复
热议问题