Skip to content

Instantly share code, notes, and snippets.

@jlogsdon
Created May 16, 2011 20:28
Show Gist options
  • Save jlogsdon/975295 to your computer and use it in GitHub Desktop.
Save jlogsdon/975295 to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# Links files in this directory to the current users home directory.
#
# If the link already exists the file will be skipped unless the -f flag is given.
real_path () {
_=`pwd`
[ -d $DIR ] && DIR=$1
[ -f $DIR ] && DIR=`dirname $1`
cd $DIR && echo `pwd` && cd $_
}
SCRIPT_DIR=$(real_path $0)
SCRIPT_PATH=${SCRIPT_DIR}/`basename $0`
FORCE=0
PREFIX=$HOME
while getopts "fp:" flag; do
case "$flag" in
f) FORCE=1 ;;
p) PREFIX=$OPTARG ;;
esac
done
PREFIX=${PREFIX%/}
for FILE_PATH in ${SCRIPT_DIR}/*; do
FILE=$(basename $FILE_PATH)
HOME_PATH=$PREFIX/.${FILE}
if [[ $FILE_PATH = $SCRIPT_PATH ]]; then
continue
fi
if [[ $FILE_PATH = $SCRIPT_PATH || ${FILE:0:1} = '.' ]]; then
continue
fi
if [[ $FORCE -eq 0 && -e $HOME_PATH ]]; then
echo Skipping $FILE_PATH
continue
fi
if [[ $FORCE -eq 1 && -e $HOME_PATH ]]; then
echo Forcably linking $FILE_PATH to $HOME_PATH
rm -f $HOME_PATH
else
echo Linking $FILE_PATH to $HOME_PATH
fi
ln -s $FILE_PATH $HOME_PATH
done
@rdpate
Copy link

rdpate commented May 16, 2011

Instead of checking FILE_PATH against SCRIPT_DIR, you can use find -mindepth 1. Though since you use -maxdepth 1, why not:

for FILE_PATH in ${SCRIPT_DIR}/*; do

@mrc
Copy link

mrc commented May 17, 2011

Beware if you run this on a non-GNU setup: -mindepth/-maxdepth are GNU find extensions.

@jlogsdon
Copy link
Author

@rdpate oh but that makes too much sense... can't have that now! (thanks for the tip!)
@mrc I have -mindepth/-maxdepth on BSD find (OSX 10.6).

@mrc
Copy link

mrc commented May 18, 2011

@jlogsdon That's lucky (I didn't know about BSD find on OSX). But it's not required by POSIX, and isn't found in some recalcitrant Unixen - for example, it's not in Solaris 10, which is a problem for, um, me :-) (but maybe it's just me!)

@jlogsdon
Copy link
Author

@mrc that's good to know! Fortunately, for FILE_PATH in ${SCRIPT_DIR}/* works just as well as @rdpate pointed out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment