I want to write my functions each in separate files, for easier version control, and source the whole lot of them in my .bashrc.

Is there a more robust way than e.g.

. ~/.bash_functions/*.sh


  • 4
    Define "robust". – Michael Homer Mar 19 '16 at 4:20
  • @MichaelHomer, how about—won't break if the directory is missing, won't break if the directory is empty, won't provide huge amounts of noise if there are a lot of files in that directory without read permissions.... – Wildcard Mar 19 '16 at 4:31
  • 1
    I do see your point, though, since if the functions/scripts are incorrectly/maliciously written it's not going to be "robust" in any meaningful way even if fulfills all of the above. The above would be enough for me. – Wildcard Mar 19 '16 at 4:31

It's simply a matter of surrounding it all with appropriate error checks:

if [ -d $FNDIR ]
    for f in $FNDIR/*.sh
       test -x $f && source $f

I'm purposely not quoting values here because I'm making an assumption that you're not going to have a home directory or script name with spaces in it. That seems to go beyond robustness and into protection against malice. Since these are scripts you are writing for yourself, I don't think we need to go that far. :)

  • On e.g. cygwin, the assumption will likely fall down due to the high number of system folders with spaces in them (My Documents, My Pictures, etc.), and on Mac OS X in e.g. your iTunes folder nearly all the directory names will have spaces after the names of the bands, but for shell scripts in home directories on Linux boxes this is a fair point. :) – Wildcard Mar 20 '16 at 9:59
  • The default home folder on Cygwin is /home/username, just as on any standard post-SVR4 POSIX system. Even if you move it to the Windows user profile directory and use Cygwin mixed-mode paths (e.g. cygpath -m), it's under c:/Users/username on every supported (i.e. post-XP) version of Windows. The story is similar for OS X: home folders are under /Users, and long user names are automatically abbreviated to a single-word short user name during installation. As for the rest of your point, why are you putting Bash shell scripts in My Pictures? – Warren Young Mar 20 '16 at 10:04
  • Fair points...but there is never a case where adding the quotes will break the code you posted. And it certainly doesn't detract from readability. Anyway, I understood your true point to be a subtle jab about my asking for robustness in sourcing files that I'm the only one in control of anyway, and that is a good point as I mentioned in comments. I still quote variables properly in my personal scripts, though. It doesn't hurt anything. – Wildcard Mar 20 '16 at 10:08
  • Fine. Quote everything. Knock yourself out. – Warren Young Mar 20 '16 at 10:09

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.