#!/bin/csh -f # make_symlink_if_necessary # ------------------------------------------------------------------------- # C shell script to create a symlink if it does not already exist with # the specified target value. This is more useful than simply ln -shfv # because it echoes the -v output only when the link ends up being # different than it was. Also, shows the old target value being discarded. # ------------------------------------------------------------------------- # Revision History: # $Log$ # ------------------------------------------------------------------------- # Collect command line options while ($#argv > 0) if ("$1" == "-h" || "$1" == "--help") then echo "Usage: $0:t [options] symlink target" echo "Options:" echo " -h = Show this help text" echo " --help = Show this help text" echo " No need for a -q (quiet) option. Just use ln -shf directly." exit 1 else if ("-" == "`echo $1:q | cut -c 1`") then echo "Error: Invalid option: $1:q" $0 --help exit 1 else # Not a recognized option. Assume it's the first argument break endif end # Collect command line arguments if ($#argv > 2) then echo "Error: Too many arguments" $0 --help exit 1 else if ($#argv < 2) then echo "Error: symlink target is required" $0 --help exit 1 else if ($#argv < 1) then echo "Error: symlink name and target are required" $0 --help exit 1 endif set rc = 0 # No error yet if (-e "$1") then # Specified file is an existing file or a symlink to an existing file. if (-l "$1") then # Specified file is a symlink set old_target = "`readlink $1:q`" if ("$old_target" == "$2") then # Nothing to do. Link already exists with specified target. else echo "Changing target of symlink $1 from $old_target to $2" # -h = Don't follow any existing link # -f = Force the creation of the link, even it already exists # -v = Verbose. Echo the creation of the link to the user. # The explicit $cwd is to make the line echoed by -v more # self-explanatory. ln -shfv $2:q $1:q set rc = $status endif else # Specified file exists, but is not a symlink echo "Error: 1st argument must be a symlink" $0 --help exit 1 endif else # Specified file doesn't exist, or is a symlink to a target that # doesn't exist. if (-l "$1") then # Specified file is a symlink set old_target = "`readlink $1:q`" if ("$old_target" == "$2") then # Nothing to do. Link already exists with specified # non-existent target. # Note: Could warn here, but choose not so since I sometimes # use this to create series of links out of order so # the first few created are not resolvable till the # others are created. else echo "Changing target of symlink $1 from unresolvable $old_target to $2" ln -shfv $2:q $1:q set rc = $status endif else # Specified file doesn't exist ln -shfv $2:q $1:q set rc = $status endif endif # Return the error code, if any, returned by the ln command exit $rc