Multiple actions in trap in ksh

466 Views Asked by At

After sudo su -, I want to have both the username and timestamp in the k-shell history list. I have the command line:

trap 'who am i|cut -d" " -f1 |tr "\n" " " && date|read -s' debug

With this command, I expect something like:

UserName Tue Oct 13 15:37:06 CDT 2015 in the history list. However it shows only Tue Oct 13 15:37:06 CDT 2015

This seems to be executing the second action date only, and ignores or overrides the first action.

How can I have the username and timestamp in the history list?

Noting that the reason why the user name is needed is that multiple users have the same impersonation right to the same service user.

3

There are 3 best solutions below

0
On BEST ANSWER

I figured out a simple solution:

  1. Create a file trapme in the service user's home directory with one line:

    who am i | cut -d" " -f1 |tr "\n" " " && date

  2. Add one line in .profile:

    trap '~/trapme | read -s' debug

this will create a line after a command with the real user login and the timestamp.

0
On

Put all the commands whose output you want to pass to read into a group:

trap '{ who am i|cut -d" " -f1 |tr "\n" " "; date; }|read -s' DEBUG
7
On

This worked for me:

$ trap 'echo this; echo that' INT
$ sleep 10
^Cthis
that
$ 

If you need complicated commands, the usual way is to use ksh -c 'compound | pipe | command' but it can get pretty tricky with quoting.

(At least in bash, the subshell is capable of invoking the parent shell's functions, so you could define a function as the commenter suggested. Not tested this with ksh).

UPDATE

This works for me:

trap 'echo $(whoami|cut -d" " -f1 |tr "\n" " " && date)' INT

Consider doing

trap 'echo "$(id -un) $(date)"' INT

Or even

trap 'date "+$(id -un) %DT%T"' INT

Etc.