How to run a command at login?

150,581

Adding the command to the end of ~/.profile should do the trick (where ~ represents your home directory).

Not ~/.bashrc, which would make it run again every time a bash shell is started. In contrast, .profile is only run by interactive login shells. See man bash and man sh for more information.

Please note that this will run not just for GUI and SSH logins, but for all logins (or at least all interactive logins), including when you log on in a virtual console.

Share:
150,581

Related videos on Youtube

Baruch
Author by

Baruch

Updated on September 18, 2022

Comments

  • Baruch
    Baruch over 1 year

    I need to run the following command (with real parameters) after login:

    ssh -f [email protected] -L 54321:example.com:54321 -N
    

    I need it only for my user, not all users on the machine. Also, I need it to run whether I login via the GUI or via SSH to a plain shell terminal. I would even like to know how to do this on machines without a GUI installed.

    Where would I put the above line to be run as explained?

  • Lucio
    Lucio about 11 years
    It could work using ~/.bash_profile?
  • Eliah Kagan
    Eliah Kagan about 11 years
    @Lucio If .bash_profile exists, then it overrides .profile for bash. I don't think the GUI uses a bash shell, though. I'll edit this to provide a link to man sh too (though I'm not sure it uses sh/dash either). .profile is universal (and typically, when .bash_profile exists, it's written so it sources .profile).
  • Lucio
    Lucio about 11 years
    Great answer. If you want to find more information you can look this SO post.
  • Frank Nocke
    Frank Nocke over 7 years
    Where would I put it -just- for login to the GUI? Nothing else.
  • mivk
    mivk about 7 years
    @FrankNocke For GUI only, you can start a script from a .desktop file in ~/.config/autostart/. Or use the gnome-session-properties GUI.
  • john_science
    john_science almost 7 years
    @EliahKagan I have a little script that is meant to be run from the commandline and print something out. But if I put that in my .profile file, the script will run and I won't see the standard out. How can I have the script open visibly? Say, to open a terminal first and then run the command?
  • Evgeni Sergeev
    Evgeni Sergeev over 4 years
    Note that a .desktop file under ~/.config/autostart can be created for you by the "Startup Applications" GUI. (Also, it might help in some cases to run the command within bash, e.g.: bash -c "xkbcomp -I$HOME/.xkb ~/.xkb/keymap/mykbd $DISPLAY" In this case, putting in the command without the bash -c part and double quotes did not work.)
  • EsmaeelE
    EsmaeelE over 4 years
    I can run added program to ~/.profile by ssh-ing to my localhost with: ssh usename@localhost