Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Fine-tuning tab completion in Bash

export IFS=$' \t\n'

help complete
open /usr/share/doc/bash/builtins.pdf

# cf. http://codesnippets.joyent.com/posts/show/1630
bind -p | egrep '^"' | egrep -v 'do-lowercase-version|self-insert' | nl
bind -p | egrep '^"' | egrep -v 'do-lowercase-version|self-insert' | grep -i complete | nl
bind -p | egrep '^"\\C' | egrep -v 'do-lowercase-version|self-insert' | grep -i complete | nl
bind -p | egrep '^"\\M' | egrep -v 'do-lowercase-version|self-insert' | grep -i complete | nl
bind -p | egrep '^"\\e' | egrep -v 'do-lowercase-version|self-insert' | grep -i complete | nl


# ~/.bashrc

echo '

shopt -s cmdhist
shopt -s histappend
export HISTIGNORE="&:clear:exit"
#export HISTIGNORE="&:[ \t]*:ls:[bf]g:history*:clear:exit"
#export HISTCONTROL=ignoredups
#PROMPT_COMMAND="history -a; ${PROMPT_COMMAND}"

# make sure Bash programmable completion is enabled
shopt progcomp > /dev/null || shopt -s progcomp
complete -d cd find
complete -G "*.txt" nano
# cf. locate /usr*.sh
#complete -G "/usr/lib/*.sh" nano

# enabe [ctrl-s] (opposite of [ctrl-r])
/bin/stty stop ""

' >> ~/.bashrc


# ~/.inputrc

echo '

# forward delete key
"\e[3~": delete-char

# [esc-d]
"\ed": kill-whole-line
#"\M-d": kill-whole-line


# up & down arrow keys
"\e[A": history-search-backward
"\e[B": history-search-forward

# use [ctrl-arrowright] or [ctrl-arrowleft] to jump between words
"\e[5C": forward-word
"\e[5D": backward-word

# op[esc-h] will show the last command that began with op
"\eh": dynamic-complete-history


# enable case-insensitive TAB-completion (for file names)
set completion-ignore-case on

# enable one-tab completion
set show-all-if-ambiguous on 
  
# turn on inline mode for tab completion
"\t": menu-complete

# shift-TAB to menu-complete backwards
# cf. http://www.tikirobot.net/wp/2006/03/29/reverse-menu-complete-in-bash/
\C-y: "\e--\C-i"
#\C-y:"\M--\C-i"


# add the missing slash when tab-completing symbolic links to directories
set mark-symlinked-directories on

#set page-completions off
#set completion-query-items 100
#set mark-directories on
#set visible-stats on
#set meta-flag on
#set input-meta on
#set convert-meta off
#set output-meta on


# ... fine-tuning magic space ...
# [esc-1], [esc-2], ...
# cf. http://codesnippets.joyent.com/posts/show/1630
"\e0": "!-1:0"
"\e1": "!-1:1"
"\e2": "!-1:2"
"\e3": "!-1:3"
"\e4": "!-1:4"
"\e5": "!-1:5"
"\e6": "!-1:6"
"\e7": "!-1:7"
"\e8": "!-1:8"
"\e9": "!-1:9"
"\er": "!-1:1-"

$if Bash
  Space: magic-space
$endif

' >> ~/.inputrc


open -a Terminal; kill -HUP $$

[cmd-n]   # new shell

# now try
cd [tab]
find [tab]
nano [tab]


# ... fine-tuning magic space ...
echo this is a very long command indeed '!!!'

[esc-0][space] [esc-1][space] [esc-r][space]


#--------------------------------------------------


# some further tab completion examples

[tab]           # list all available commands
[esc][esc]      # alternative
[esc-?]          # list all possible completions
[esc-*]          # insert all possible completions after the cursor

ds[tab]          # list all available commands beginning with ds
ds[esc][esc]
ds[esc-?]
ds[esc-*]

cd ~/Des[tab] 
#cd ~/Desktop
cd [tab]      # list all subdirectories in ~/Desktop
cd [esc][esc]
cd [esc-?]
cd [esc-*]

$[tab]       # list all set system variables
~[tab]       # list users
~[esc][esc]   # alternative
*[tab] 
=[tab]
/[tab]
@[tab]      # list entries form /private/etc/hosts


# disable completion for a single command
help complete
complete -r cd[tab]
cd[tab]


#-------------------------------------------


# man [tab]

function listmans() {
for dir in $(/usr/bin/man -W | /usr/bin/tr ':' '\n'); do 
   /usr/bin/find -x "${dir}" ! -type d -name "*.*" -print0 2>/dev/null | /usr/bin/xargs -0 /usr/bin/basename | /usr/bin/sort -u
done 
return 0
}

listmans | less
listmans | sed -E -n 's/^.+(\.[^\.]+)$/\1/p' | sort -u
listmans | sed -E -n 's/^.+(\.[^\.]+\.gz)$/\1/p' | sort -u
listmans | sed -E -n 's/^.+(\.[[:lower:]]+)$/\1/p' | sort -u
listmans | sed -E -n 's/^.+(\.[[:alnum:]]+)$/\1/p' | sort -u


complete -W "$(
   for dir in $(/usr/bin/man -W | /usr/bin/tr ':' '\n'); do 
      /usr/bin/find -x "${dir}" ! -type d -print0 2>/dev/null | /usr/bin/xargs -0 /usr/bin/basename | \
      /usr/bin/sed -E -n 's/^(.+)\.[[:digit:]]+$|\.[[:digit:]]+[[:lower:]]+$|\.[[:lower:]]+$|\.[^\.]+\.gz$/\1/p' | /usr/bin/sort -u

      #/usr/bin/find -x "${dir}" \( -type f -or -type l \) -print0 2>/dev/null | /usr/bin/xargs -0 /usr/bin/basename | \
      #/usr/bin/sed -E -n 's/^(.+)\.[[:digit:]]+$|\.[[:digit:]]+[[:lower:]]+$|\.[[:lower:]]+$|\.[^\.]+\.gz$/\1/p' | /usr/bin/sort -u
   done
)" man

man ds[tab]
man ssh[tab]

man m[esc][esc]
man m[esc-?]
man m[esc-*]

man chmod 2[esc-t]      # swap the positions of two words


#---------------------------------------------


# open -a [tab]

# cf. http://codesnippets.joyent.com/posts/show/1643
/usr/bin/sudo /bin/ln -is "$(/usr/bin/locate lsregister | /usr/bin/head -n 1)" /bin/lsregister

function opena() { /usr/bin/open -a "$@"; return 0; }
alias opena='/usr/bin/open -a'

# version 1
complete -W "Mail Safari Terminal Address\\\\\\ Book" opena
opena A[tab]

# version 2
time -p lsregister -dump | sed -E -n -e '/Applications/{s/^.+ ((\/Applications|\/Developer\/Applications).+\.app)$/\1/p;}' | \
        sed 's/ /\\ /g' | xargs basename -s '.app' | sed 's/ /\\\\\\ /g' | nl

time -p lsregister -dump | sed -E -n -e '/\/Applications/{s/^.+ ((\/Applications|\/Developer).+\.app)$/\1/p;}' | \
        sed 's/ /\\ /g' | xargs basename -s '.app' | sed 's/ /\\\\\\ /g' | nl


complete -W "$(
/bin/lsregister -dump | /usr/bin/sed -E -n -e '/\/Applications/{s/^.+ ((\/Applications|\/Developer).+\.app)$/\1/p;}' | \
     /usr/bin/sed 's/ /\\ /g' | /usr/bin/xargs /usr/bin/basename -s '.app' | /usr/bin/sed 's/ /\\\\\\ /g'
)" opena

opena S[tab]
opena C[esc][esc]
opena [esc-.]
opena [esc-*]



Further information:

- Working more productively with bash 2.x/3.x
- Bash complete examples (Apple Darwin source code)
- Mac Bash Completion
- Create on-the-fly hostname lists for ssh tab completion
- bash: completion (with ssh)
- Custom Tab Completion
- CLI Magic: Bash complete
- My Bash Profile
- HOWTO: make life easier in terminal using bash aliasing
- Cdots - Change directory back - 1-7 times - and forth with TAB-completion
- some handy terminal.app crud
- cd effectively (links)
- Tapping the Bash command line history
- Handling control characters on the command line

open or cd to the directory of a file path

# open directory of a file path
# can be used together with the [esc-.] key sequence
function odf() { /usr/bin/open "$(/usr/bin/dirname "$@")"; return 0; }

# cd to the directory of a file path
function cdf() { cd "$(/usr/bin/dirname "$@")"; return 0; }


ls -l /Library/Desktop\ Pictures/Nature/Tranquil\ Surface.jpg
ls -l /System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/ExecutableBinaryIcon.icns 

odf [esc-.]
cdf [esc-.]


odf /System/Library/SystemProfiler/SPFirewallReporter.spreporter/Contents/Resources/
cdf /System/Library/SystemProfiler/SPFirewallReporter.spreporter/Contents/Resources/English.lproj/Localizable.strings

"openterminal" contextual menu item with Automator

Right-click on a file or folder in a Finder window and select Automator -> openterminal to open it in Terminal.app.
(i.e. cd to the folder or open the file in the nano text editor)

open -a Automator

#--------------------------------------------------

Drag or add actions here to build your workflow:
Library: Finder -> Action: Get Selected Finder Items
Library: Automator -> Action: Run Shell Script
                                 - Shell: /bin/sh
                                 - Pass input: as arguments


if [[ $# -gt 1 ]]; then exit 0; fi

if [[ -d "$@" ]]; then

   printf "%s" "$@" | /usr/bin/pbcopy
   #/usr/local/bin/cpath # cf. http://osxutils.sourceforge.net

   /usr/bin/open -a Terminal

   /usr/bin/osascript -e 'tell application "Terminal" to do script with command "printf \"\\e[8;26;115;t\"; printf \"\\e[3;300;240;t\"; cd \"$(/usr/bin/pbpaste)\"; /usr/bin/clear" in (first window whose name contains " ")'

# alternative without /usr/bin/clear (experimental)
# requires:
# defaults write com.apple.Terminal Autowrap NO
# or:
# Terminal menu -> Window Settings ...  -> Buffer -> in the Scrollback 
# section check the box next to "Wrap lines that are too long" 
# -> click "Use Settings as Defaults"

#   /usr/bin/osascript -e 'tell application "Terminal" to do script with command "cd \"$(/usr/bin/pbpaste)\"; /usr/bin/tput cup 0 0; /usr/bin/tput dl1; /usr/bin/tput el; /usr/bin/tput dl1; /usr/bin/tput el" in (first window whose name contains " ")'

   exit 0

elif [[ -r "$@" ]]; then 

   printf "%s" "$@" | /usr/bin/pbcopy

   /usr/bin/open -a Terminal

   /usr/bin/osascript -e 'tell application "Terminal" to do script with command "printf \"\\e[8;26;115;t\"; printf \"\\e[3;300;240;t\"; /usr/bin/clear; /bin/sleep 0.3; /usr/bin/nano \"$(/usr/bin/pbpaste)\";" in (first window whose name contains " ")'

exit 0

fi

exit 0


# now save the openterminal Automator workflow as a contextual menu item:
# Automator -> File -> Save As Plug-in ... -> Save Plug-in As: openterminal -> Plug-in for: Finder -> click Save


#--------------------------------------------------


open -a Automator ~/Library/Workflows/Applications/Finder/openterminal.workflow

/usr/bin/automator ~/Library/Workflows/Applications/Finder/openterminal.workflow >/dev/null 2>&1


More on how to cd effectively:

- cdto - Finder Toolbar button to open a Terminal window
- History of visited directories in BASH
- bash Tips and Tricks: $CDPATH
- Bash Shell Customisation: cdable_vars
- The Definitive Guide to Bash Command Line History
- Working Productively in Bash's Vi Command Line Editing Mode (with Cheat Sheet)
- Leopard's bash auto-completion vs. symlinked directories
- zg.rb (ZoomGo)
- fuzzy_file_finder.rb
- cd to Directory within Terminal
- Pimp my shell
- Per-directory bash history
- Terminal Tricks: A Fuzzy cd Command
- Cdots - Change directory back - 1-7 times - and forth with TAB-completion
- Fine-tuning tab completion in Bash
- recd on sourceforge
- recd - cd again via regular expression
Download with: curl -L -O http://heanet.dl.sourceforge.net/sourceforge/recd/recd.sh

Burn ISO osx

Open Terminal and type:
hdiutil burn image.iso