10

I have written some scripts and stored them in my ~/bin folder. I'm already able to run them just by calling their title during a shell session. However, they aren't running interactively (I mean, my ~/.bashrc aliases are not loaded).

Is there a way to mark them to run interactively by default? Or must I source ~/.bashrc inside of them to use any aliases defined there?

Other alternatives are welcome!

6
  • 5
    Do you want to make them run "interactively" or do you want them to load ~/.bashrc by default? Because interactive shells come with some surprises, like ignoring SIGTERM
    – user313992
    Commented Feb 24, 2020 at 16:57
  • By now, I'm actually just looking for a way to use bashrc's aliases in the scripts even when call them through bin reference
    – artu-hnrq
    Commented Feb 25, 2020 at 2:56
  • 1
    Consider changing your aliases into shell functions. Unlike aliases, functions are available when the shell is noninteractive. Functions aren't particularly more complex than aliases to write. alias hw='echo hello world' vs hw() { echo hello world; }
    – kojiro
    Commented Feb 25, 2020 at 13:17
  • Well, I've tested here, but without use -i flag, bashrc functions are not loaded just like its aliases
    – artu-hnrq
    Commented Feb 25, 2020 at 15:58
  • 1
    @ArthurHenriqueDellaFraga then you better shopt -s expand_aliases; . ~/.bashrc at the beginning of your script (~as in the non-accepted answer). You still have to modify a script to change its shebang, and as I already said, the interactive mode comes with some changes in behaviour which are not desirable in a shell script. And, as @kojiro said, better use functions instead of aliases. Aliases only have advantages when used in an real interactive shell, I cannot think of any reason to use them in a script.
    – user313992
    Commented Feb 27, 2020 at 5:18

2 Answers 2

13

If you add the -i option to your hashbang(s) it will specify that the script runs in interactive mode.

#!/bin/bash -i

Alternatively you could call the scripts with that option:

bash -i /path/to/script.sh
8

Sourcing your .bashrc is not a good idea. You could create a .bash_alias file with your alias and then source that file in your script and use shopt

something like:

shopt -s expand_aliases
source ~/.bash_alias

Bash man page states:

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt (see the descrip‐ tion of shopt under SHELL BUILTIN COMMANDS below).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .