1

Create an alias named mylogin that lists the specified number of most recent logins made by the user. For example, if a user enters mylogin 8 in the command line, the system will list the eight latest logins from the user. The alias should work for any user without any modification.

I am able to do

last username | head -8

to get last 8 logins of username, where I replace my name with username but I can't figure how to make it work for any user

Bodo
  • 9,287
  • 1
  • 13
  • 29

1 Answers1

0

To make your command work with any user try

last $(whoami)| head -8

I replaced the parameter username in your command with $(whoami) which is the output of whoami. Command whoami prints the user name associated with the current effective user ID. When you run this without using sudo or other means for changing the effective user ID it should be the login name of the current user.

or

last -n 8 $(whoami)

If your last command supports option -n 8 or simply -8 you can specify the number of lines to be printed without piping through head. Note that this may add a line stating when the wtmp file has been started. With | head -8 this additional line will get removed if there are enough login lines above it.

alias or function

According to https://stackoverflow.com/a/7131683/10622916 you cannot pass an argument to an alias. Arguments will be appended to the expansion of the alias.

So it's not possible to insert the argument into the alias expansion or combine it with - to build an option.

If you need an alias, not a function, you can use

alias mylogin='last $(whoami)|head -n'

Then you can call

mylogin 8

which will be expanded to

last $(whoami)| head -n 8

This solution has the drawback that you will get an error from head when you call

mylogin

without argument because this gets expanded to

last $(whoami)| head -n

To avoid this error you could use a function instead of an alias.

mylogin () {
    if [ -n "$1" ]
    then
        last -n "$1" $(whoami)
    else
        last $(whoami)
    fi
}

In the function you can also use

last $(whoami) | head -n "$1"

instead of

last -n "$1" $(whoami)
Community
  • 1
  • 1
Bodo
  • 9,287
  • 1
  • 13
  • 29