6

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!

  • 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 – pizdelect Feb 24 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 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 Feb 25 at 13:17
  • Well, I've tested here, but without use -i flag, bashrc functions are not loaded just like its aliases – artu-hnrq Feb 25 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. – pizdelect Feb 27 at 5:18
4

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
|improve this answer|||||
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).

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.