8

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!

terdon
  • 234,489
  • 66
  • 447
  • 667
artu-hnrq
  • 267
  • 4
  • 14
  • 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` –  Feb 24 '20 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 Feb 25 '20 at 02: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 Feb 25 '20 at 13:17
  • Well, I've tested here, but without use [`-i` flag](https://unix.stackexchange.com/a/569447/364080), `bashrc` functions are not loaded just like its aliases – artu-hnrq Feb 25 '20 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. –  Feb 27 '20 at 05:18
  • Thanks a lot for all tips, I'll keep improving my strategy and learning about all UNIX environment – artu-hnrq Feb 27 '20 at 15:20

2 Answers2

7

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
jesse_b
  • 35,934
  • 12
  • 91
  • 140
7

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).

BANJOSA
  • 701
  • 3
  • 14