0

I'm on a Linux machine using screen, and I'm attempting to write a (fairly portable) function which runs a bash function in a new, detached screen session which automatically closes upon completion. I've had some success, but I noticed the following behavior:

If I include the definition of mail_submit() in my ~/.bashrc file, I can run

    mail_submit foo

in the terminal, and also I can access the alias in a new screen session:

    screen -S test
    mail_submit foo

However, the following command does not work:

    screen -d -m -S test sh -c 'mail_submit foo'

presumably because sh -c starts a fresh shell that has no knowledge of my ~/.bashrc profile. So, I can use the following fix:

    screen -d -m -S test sh -c 'source ~/.bashrc; mail_submit foo'

which does work.

But if I want to wrap this functionality up into a bash alias (which is my ultimate goal here), this will cause a weird self-referential situation.

Question: What is an easy way to either have sh -c know the location of my ~/.bashrc profile, or use a variant of sourcing the file and creating an alias?

EDIT: I could save the shell script in my home directory, and create an alias which runs

    screen -d -m -S test bash -c '~/mail_submit.sh $1'

but I'd still be curious to hear other possible fixes.

chriswhite
  • 1,370
  • 10
  • 21

2 Answers2

2

Do you mean screen -d -m -S test bash -c 'mail_submit foo'? It looks like you're trying to run the command with the shell (sh), and not the bourne again shell (bash), which is the shell interpreter which actually reads the ~/.bashrc profile.

Edit: The .bashrc file is not being sourced by default because screen does not create the bash process as a login shell, which is when the .bashrc file is read. Creating a .screenrc file with the line defshell -bash will create the bash process as a login shell instead, which will then call the .bashrc file.

Incognito
  • 189
  • 2
  • 10
  • Good catch; unfortunately the problem persists, and is likewise fixed when I explicitly source `~/.bashrc`. – chriswhite Mar 01 '16 at 14:48
  • Try setting up a ~/.screenrc file with `defshell -bash` in it, which makes bash run as a login shell, which will call the ~./.bashrc file, since by default, screen will not run bash as a login shell (which is when the .bashrc file is read). See this post for more information: https://bbs.archlinux.org/viewtopic.php?id=82519 – Incognito Mar 01 '16 at 14:57
2

A default ~/.bashrc contains this ([[ "$-" != *i* ]] && return) little piece of code on top of it (or somewhere else in the upper part). This line will prevent the ~/.bashrc from beeing sourced if the bash shell doesn't run in interactive mode.

You could:

  1. Remove this line
  2. Create a new file which will only contain the alias you need and source that
  3. Create a little bash script instead of an alias and run that
Mischa
  • 1,303
  • 12
  • 24