My .bashrc has the following permissions: -rwxr-xr-x

So it's labeled "executable". I should therefore be able to just run it.

But when I try

$ ./.bashrc

I get:

./.bashrc: line 6: return: can only `return' from a function or sourced script

Lines 5 and 6 of .bashrc:

# If not running interactively, don't do anything
[ -z "$PS1" ] && return

I googled the issue, and the following "source" command does what I need perfectly:

$ source .bashrc


1- Why can't I run ./.bashrc directly and what does this line do:

[ -z "$PS1" ] && return

2- What are 'sourced scripts' and what does the 'source' command do exactly? (no man pages on my system for 'source')

  • Source is a bash builtin, you'll find documentation on the bash man page. – JShorthouse Apr 18 '19 at 15:12

The difference between sourcing a dot-script with source (or with ., which is the standard command) and running it as its own script has been discussed before.

See e.g. "What is the difference between sourcing ('.' or 'source') and executing a file in bash?". It comes down to the difference between running a script in its own separate environment (without source or .) and running a set of commands in the current shell environment, which is what you want to do if you need to set environment variables and shell options etc. for the current shell. Setting a shell option or exporting a variable in a script (not run with source or .) will not affect the parent shell.

The particular test that you ask about,

[ -z "$PS1" ] && return

will return from the dot-script if the primary prompt, $PS1, is empty. This is one way of testing whether the current shell session is interactive or not. If it's not interactive, the PS1 variable will not be set and the prompt will be empty, in which case, the rest of the script (presumably) does not need to be run as it maybe only deals with things that needs initialising in an interactive shell.

A dot-script would need to use return rather than exit as an exit would terminate the current shell session, which is the same as the session that invoked the script with source or .. A dot-script thus behaves a whole lot like a shell function.

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