ported from zsh to bash
bugfix: device index + error handling