oft: Bash function for opening a specific filetype
Here’s another simple Bash function that I’ve used so much recently I thought I should share. It’s called oft
, which stands for Open File Type, and can be used as a standalone shell script or as a function in your .bash_profile
. When run, it looks in the current directory for files with extensions that match (or partially match) the first argument and opens them.
My most obvious use case is Xcode projects, where I may have dozens (and dozens) of files, but there’s only one .xcodeproj
file (folder). I don’t always know the name of the project in the folder, but if I run oft xco
it will open it without my having to search. If there is more than one result, it gives you a numeric menu to select the file you want to open. You can cancel, select a single file or “Open ALL” from that menu. If you run oft
with no arguments, it will read a (partial) extension from a prompt.
This is a script born of laziness (so many good ones are, though). You can accomplish the same with an ls *.ext
, spot the file and open filename.ext
. This is just faster and better for me when I’m working with less-than-optimal amounts of sleep.
# Open filetype
# Finds every file in folder whose extension starts with the first parameter passed
# if more than one file of given type is found, it offers a menu
oft () {
if [[ $# == 0 ]]; then
echo -n "Enter an extension or partial extension: "
read extension
fi
if [[ $# > 1 ]]; then
echo "Usage: oft [(partial) file extension]"
return
fi
extension=$1
ls *.*$extension* > /dev/null
if [[ $? == 1 ]]; then
echo "No files matching \"$extension\" found."
return
fi
declare -a fileList=( *\.*$extension* )
if [[ ${#fileList[*]} -gt 1 ]]; then
IFS=$'\n'
PS3='Open which file? '
select OPT in "Cancel" ${fileList[*]} "Open ALL"; do
if [ $OPT == "Open ALL" ]; then
read -n1 -p "Open all matching files? (y/N): "
[[ $REPLY = [Yy] ]] && $(/usr/bin/open ${fileList[*]})
elif [ $OPT != "Cancel" ]; then
$(/usr/bin/open "$OPT")
fi
unset IFS
break
done
else
$(/usr/bin/open "${fileList[0]}")
fi
}
Ryan Irelan has produced a series of shell trick videos based on BrettTerpstra.com posts. Readers can get 10% off using the coupon code TERPSTRA
.