Search code examples
linuxrpmpackagingrpm-spec

Get user while packaging rpm


I am trying to get USER-NAME in my spec file while packaging rpm. "$HOME" command gives me USER in case of running in bash. Spec file also works like bash but when I run the similar command in %post section of spec file, I get 'root' as output. This might be happening as user run rpm package using sudo.

Kindly help how to get USER name in Spec file


Solution

  • In the .spec a %define macro would get you the username. Here is an example, how it might look like inside the .spec file.

     Source0: %{name}-%{version}.tar.gz
    
     # User defined function to get who built the RPM
     %define packagername %(who am i | awk '{print $1}')
    
     %description
     ...
     %prep
     ...
    
     # Then in the post section call the macro %{packagername}
     %post
     echo "Packager is: %{packagername}"
    

    Note, %post section will be run only when install the .rpm file. Above will print the information into stdout.

    Output

    $ sudo rpm -ivh simple-0-1.x86_64.rpm
    Preparing...                ########################################### [100%]
       1:simple                 ########################################### [100%]
    Packager is:  iamauser
    

    In order to use this macro globally on the system, one can define it inside /etc/rpm/macros.<somename>.

    $ cat /etc/rpm/macros.username
    # Get who is the packager
    %packagername %(who am i | awk '{print $1}')
    

    With the global definition one doesn't need to define it inside the .spec file.

    If you don't have permission to write into /etc/rpm, then defining it in ~/.rpmmacros file would make that macro available only to you.