In Ubuntu I like having

shopt -s autocd

in my .bashrc file for automatic CD'ing with typing 'cd', i.e. just type the directory name (and probably use tab completion too) and press return and be cd'd to the directory if it exists.

On OSX this isn't valid in my .bashrc

How can I do a 'depends on' for this? So that I can share and maintain just one .bashrc between the two OS's ?

I know for a file I can do stuff like:

if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
    . /etc/bash_completion

and for an application like tmux that depends on screen I can do

if [[ ! $TERM =~ screen ]]; then
  if [ -n "$(type -P tmux)" ]; then
    exec tmux

but I can I do this kinda thing for whether I can do shopt -s autocd ?

  • 1
    check $BASH_VERSION >= 4 perhaps? Seems poor way though. Apr 12 '14 at 18:21
  • Switching on uname -s might be enough.
    – Mat
    Apr 12 '14 at 18:34
  • Is it a fatal error? If not, just silence it.
    – Mikel
    Apr 12 '14 at 18:59
  • 1
    @Michael testing for the feature or bash version seems much better than checking the OS. What if you upgrade the version of bash on your Mac? (Which is probably the better solution BTW.)
    – Mikel
    Apr 12 '14 at 19:00
  • 1
    Yes, that's cause I'm an idiot. Sorry, try the updated answer, the -eq does integer comparison, not string. [[ $(uname) = dsdss ]] && echo 'y' will not echo anything.
    – terdon
    Apr 12 '14 at 20:01

autocd was introduced into bash with version 4. So, a general cross-platform solution should be:

[ "${BASH_VERSINFO[0]}" -ge 4 ] && shopt -s autocd

${BASH_VERSINFO[0]} is bash's major version. The minor version, should you ever need it, is ${BASH_VERSINFO[1]}. See man bash for more on BASH_VERSINFO.


It's as simple as

shopt -s autocd 2>/dev/null

If you want to see whether an option is available but not change its value, call shopt without -s or -u:

if shopt autocd >/dev/null 2>/dev/null; then …

A simple approach would be to check the OS name and act accordingly. I don't know what uname will return on OSX but presumably it will be different. You can therefore do something like this:

 [[ $(uname) = Linux ]] &&  shopt -s autocd

That said, are you sure you need to do this? OSX runs login shells by default and the ~/.bashrc is ignored unless you have modified your ~/.profile to source it. Therefore, if you have something in your ~/.bashrc, it will only run on Linux anyway.

  • +1 for useful info. downvote not from me. Apr 13 '14 at 17:17
  • @MichaelDurrant heh thanks :) The original downvote was merited since I was using -eq instead of =.
    – terdon
    Apr 13 '14 at 17:22

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.