2

I'm using a solution described here to log my shell sessions, by adding this to the end of /etc/bash.bashrc:

test "$(ps -ocommand= -p $PPID | awk '{print $1}')" == 'script' || (script -f /var/log/shellog/$USER-$(date -u +%Y.%m.%d-%H:%M:%S).${HOSTNAME:-$(hostname)}.$$.log)

This works fine, however, when I exit the shell, I have to exit twice: once from the script, and once from the shell:

Last login: Wed Aug  6 12:43:29 2014 from *****
Script started, file is /var/log/shellog/camilstaps-2014.08.06-10:43:40.cs.localdomain.16048.log
camilstaps@cs:/$ exit
exit
Script done, file is /var/log/shellog/camilstaps-2014.08.06-10:43:40.cs.localdomain.16048.log
camilstaps@cs:/$ exit
exit

I found this, and tried modifying the line in /etc/bash.bashrc accordingly, but this doesn't change anything:

test "$(ps -ocommand= -p $PPID | awk '{print $1}')" == 'script' || (script -f /var/log/shellog/$USER-$(date -u +%Y.%m.%d-%H:%M:%S).${HOSTNAME:-$(hostname)}.$$.log && exit)

I suppose it's because I have to test that I'm not in script already (without the test it keeps making new scripts). But how can I make that I don't have to exit twice?

  • What does `ps -ocommand= -p $PPID` return ? – Valentin Bajrami Aug 06 '14 at 11:11
  • @val0x00ff `script -f /var/log/shellog/camilstaps-2014.08.06-11:12:11.cs.localdomain.16164.log` –  Aug 06 '14 at 11:12
  • so that will always match. With awk you are printing the first field which is `script`. Everything after `||` will never get executed. – Valentin Bajrami Aug 06 '14 at 11:16
  • @val0x00ff well, it is executed when I start the session, of course. I'm not sure if I understand what you're getting at. –  Aug 06 '14 at 11:18
  • Camil, what does this do: `[[ "$(ps -ocommand= -p $PPID | awk '{print $1}')" = script ]] || { script -f /var/log/shellog/$USER-$(date -u +%Y.%m.%d-%H:%M:%S).${HOSTNAME:-$(hostname)}.$$.log && exit ;}` I mean, try to put the code within `[[ .. ]]` keyword and group the command after `||` – Valentin Bajrami Aug 06 '14 at 11:23
  • 1
    @val0x00ff that works! Thank you very much. I don't understand why exactly, but I'll try to figure it out. Could you add it as an answer? –  Aug 06 '14 at 11:25
  • 1
    Camil, the command you had within `()` will run in a subshell. This means another process is created. Read more about it here: http://mywiki.wooledge.org/SubShell – Valentin Bajrami Aug 06 '14 at 11:31
  • @val0x00ff I see, thank you very much, also for the explanation. –  Aug 06 '14 at 11:32

1 Answers1

1

As requested. The following should work

[[ $(ps -ocommand= -p $PPID | awk '{print $1}') = script ]] || { script -f /var/log/shellog/$USER-$(date -u +%Y.%m.%d-%H:%M:%S).${HOSTNAME:-$(hostname)}.$$.log && exit ;} 
Valentin Bajrami
  • 9,244
  • 3
  • 25
  • 38