Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Hi I am curious if it is possible to execute a bash script inside bash rc. It would seem to create a infinite loop unless there was some way to tell it to not try and start a new shell.

Here is an example

bash_script.sh:

#!/bin/bash
echo Hello World

.bashrc

export HELLO_WORLD=$(bash_script.sh)    
share|improve this question

4 Answers 4

Ok I figured out how to do this. In .bashrc just do:

export HELLO_WORLD=$(source bash_script.sh)
share|improve this answer
1  
There's no reason, so far as I can tell, for you to have it assign the result of that script to a variable. You could just as easily have the line source bash_script.sh in your .bashrc –  HalosGhost May 11 at 2:38

Put this as line 1:

[ -z "$PS1" ] && return # If not interactive, exit
share|improve this answer
1  
This isn't a very good test as PS1 could be set even in non-interactive mode. The way to test for interactive mode in bash is by doing [[ "$-" == *i* ]] && echo "I'm interactive" –  Patrick May 11 at 2:31

You do not need to do anything. Simply launching a bash script will not cause your .bashrc to be invoked.

The only time your .bashrc will get invoked is if bash is interactive. When you launch a script, that script is not interactive.

From the bash man page:

An interactive shell is one started without non-option arguments and without the -c option whose standard input and error are both connected to terminals (as deter‐ mined by isatty(3)), or one started with the -i option. PS1 is set and $- includes i if bash is interactive, allowing a shell script or a startup file to test this state.

The important bit here is "started without non-option arguments". When you launch a script, the first argument to bash is the path to that script. Thus it has a non-option argument and is not interactive.

share|improve this answer

A script is executed by a non-interactive shell, while .bashrc is only automatically sourced by interactive shells.


There is a way to trigger an infinite loop, though. Every bash shell, interactive or not, checks if the variable BASH_ENV is set and, if so, uses its value as the name of a file to source. In this case, executing a bash script from this file would result in the infinite loop, so are must be taken. In practice, though, this script would (as its name suggests) simply be used to set environment variables for use by the shell, not execute arbitrary code.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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