6

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
fi

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

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

3 Answers3

3

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.

John1024
  • 74,655
2

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 …
0

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.

terdon
  • 242,166