Scott Anderson
Scott Anderson

Reputation: 693

How to have a part of `~/.bash_profile execute only on shell open?

I have been searching high and low for this answer, maybe it is a dead-end road I don't know. I am running Ubuntu 20.04 and I currently have this bash_profile:

export MAG_DIR="/var/www/html/magento-2"
export NGINX_ERR="/var/log/nginx/error.log"
export MAG_ERR="/var/www/html/magento-2/var/log/system.log"
export XDEBUG_LOG="/var/log/xdebug/xdebug.log"
export PHP_FPM_CONF="/etc/php/7.3/fpm/php.ini"
export PHP_CLI_CONF="/etc/php/7.3/cli/php.ini"
export PHP_LOG="/tmp/php-error.log"

function wgrep () {
    grep -nA 3 -B 3 $1;
}

function findfirst () {
    find $1 -name $2 | head -n 1
}

function catfirst () {
    cat $(find $1 -name $2 | head -n 2)
}

function t30 {
    tail -fn 30 $1;
}

function fac {
    git fetch && git checkout $1;
}

#if [ -f ~/.bashrc ]; then
#  . ~/.bashrc
#fi

if [ -f ~/.bash_vars ]; then
    . ~/.bash_vars
fi

export PS1="\D{%H:%M:%S} \[\e]0;\u@\h: \w\a\] 🏠 ${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ "


#local setup
[ ! -f $PHP_LOG ] && touch $PHP_LOG
chmod 777 $PHP_LOG
cd $MAG_DIR
clear

I want to migrate the last lines, which set up the shell for a new session into a separate script that runs only when the shell is first created.

I like to tweak my /.bash_profile whilst working, it is sourced in ~/.bashrc so if I am making a modification in ~/.bash_profile and want to see the changes, currently I will get booted back to my dev directory. Also it will make redundant changes to files like log files. These login 'setup' actions will probably change over time

I am aware that .bash_login exists but I can't seem to get it to work for me. I set my terminal preferences to 'run command as login' or whatever the settting is and it then ignores my ~/.bash_profile (which is probably intended behaviour I guess)

p.s: `~/.bash_vars contains random variables that I want to vary from env to env or to hold some secrets, as this bash_profile is versioned

Upvotes: 0

Views: 235

Answers (1)

dash-o
dash-o

Reputation: 14493

From the OP question, the goal is to have the tail of the .bash_profile execute only on the initial shell, and not execute on sub shells. One possible solution is to track the one-time execution in exported variables.

if [ ! "$FIRST_TIME" ] ; then
   export FIRST_TIME=YES
   [ ! -f $PHP_LOG ] && touch $PHP_LOG
   chmod 777 $PHP_LOG
   cd $MAG_DIR
   clear
fi

Given that in this example, '.bashrc' is sourcing '.bash_profile', the commands that are protected by "FIRST_TIME" will not be executed on interactive subshell.

Upvotes: 1

Related Questions