Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

This shell script is mostly the work of other people. It has gone through several iterations, and I have tweaked it slightly while also trying to fully understand how it works. I think I understand it now, but I don't have confidence to significantly alter it on my own and risk losing data when I run the altered version. So I would appreciate some expert guidance on how to improve this script.

The changes I am seeking are:

  1. make it even more robust to any strange file names, if possible. It currently handles spaces in file names, but not newlines. I can live with that (because I try to find any file names with newlines and get rid of them).
  2. make it more intelligent about which file gets retained as the actual inode content and which file(s) become sym links. I would like to be able to choose to retain the file that is either a) the shortest path, b) the longest path or c) has the filename with the most alpha characters (which will probably be the most descriptive name).
  3. allow it to read the directories to process either from parameters passed in or from a file.
  4. optionally, write a long of all changes and/or all files not processed.

Of all of these, #2 is the most important for me right now. I need to process some files with it and I need to improve the way it chooses which files to turn into symlinks. (I tried using things like the find option -depth without success.)

Here's the current script:


# clean up known problematic files first.
## find /home -type f -wholename '*Icon*
## *' -exec rm '{}' \;

# Configure script environment
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
set -o nounset

# For each path which has multiple links
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# (except ones containing newline)
while IFS= read -r path_info
   #echo "DEBUG: path_info: '$path_info'"
   if [[ $last_inode != $inode ]]; then
       printf "ln -s\t'$path_to_keep'\t'$path'\n"
       rm "$path"
       ln -s "$path_to_keep" "$path"
done < <( find "$dir" -type f -links +1 ! -wholename '*
*' -printf '%i:%p\n' | sort --field-separator=: )

# Warn about any excluded files
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
buf=$( find "$dir" -type f -links +1 -path '*
*' )
if [[ $buf != '' ]]; then
    echo 'Some files not processed because their paths contained newline(s):'$'\n'"$buf"

exit 0
share|improve this question

1 Answer 1

up vote 2 down vote accepted


One simple change to not die on file names that start on - is to add -- (means "now all options have been given, only positional arguments left") before the file name arguments start, e.g.

rm -- "$path"
ln -s -- "$path_to_keep" "$path"

and so on.


To count alpha ("alphanumeric" is probably what you really want) characters in a file name you could do

numberofalnum=$(printf -- "$path" | tr -cd [:alnum:] | wc -m)

To count path depth, you could try to just count occurences of '/' in the filename. A caveat could be that /home///daniel is equivalent with /home/daniel, but find won't output unnecessary multiple slashes, so it will be alright.

depth=$(printf -- "$path" | tr -cd / | wc -m)

One could also collapse multiple slashes by running tr -s / after printf. Combining -s, -c and -d in this way in a single invocation is not really possible, it seems.

In this case, since find is already used in this way in the script, just adding a : separated field in the -printf output with %d will print the depth directly, as noted below in comment.


To read directories as arguments from the command line, see this minimal snippet:

while [ $# -ne 0 ]; do
    printf -- 'Argument %d: %s\n' "${i}" "${1}"

($i is just a counter to show you what is happening)

If you wrap your logic in such a while loop, you can access the first argument as ${1}, then use shift which pops the first item off the argument list, and then iterate again and now ${1} is the originally second argument. Do this while the argument count $# is not 0.


To read the arguments from a file, wrap it instead like

while read line; do
    printf -- 'Argument %d: %s\n' "${i}" "${line}"
done < "${1}"

Tip: instead of just increasing indent and wrapping the whole file logic that way, create functions of the current logic and call them at the end of the script. This will easily enable you to choose between either giving directories as arguments or reading them from a file without duplicating code in your script.



printf 'My descriptive log message for path %s\n' "${path}" >> "${logfile}"

in the logic blocks where you have decided to take action or not. Set $logfile earlier to a wanted log path.

share|improve this answer
thank you. I have a couple questions. I'll focus on item 2 first. For finding the most descriptive names, I want to use something like printf -- "$(basename "$path")" | tr -cd [:alpha:] | wc -m in the line done <<(find ... and sort first on inode number, then on alpha char count. I just can't glue it all together. Can you help? –  MountainX Mar 29 '12 at 16:48
regarding path depth, find has the printf % directive %d File's depth in the directory tree which I could add to the existing find command in done <<(find .... Then I just need to be able to choose whether to sort on alpha char count or path depth. Not sure how to do that. –  MountainX Mar 29 '12 at 16:52
To sort on a different key, e.g. the second, use 'sort -t: -k2'. By setting the key number according to alnum or path depth preference you can choose sorting order. You can also sort on multiple keys using multiple -k arguments. The syntax is a bit weird, but 'sort -k 1,1 -k 3,3' sorts on field 1, then field 3 (the ,1 is needed to tell sort to "stop looking" after field 1). This will enable you to sort on inode and path depth as in your first comment, and on a chosen field as in your second comment. –  Daniel Andersson Mar 29 '12 at 17:25
This code basename "$myfilename" | tr -cd [:alpha:] | wc -m gives me the alpha char count of the filename, but I can't figure out how to get that into the find output so I can sort on it. In other words, I need a find command that will printf %i:%d:%p\n PLUS print this alpha char count. Then I'll sort. I can't figure out how to integrate those find/printf commands. This was the essence of my first comment/question above. Thanks. –  MountainX Mar 29 '12 at 18:07
I think you are really nearing the limit of what one can cram into a single pipe in that way. If you really want to keep the structure of the script, you probably need to throw in awk in the find pipe, where you can certainly do the tr -cd | wc -m dance and more. You are not really gaining much in performance from the pipe any longer since sort needs all input before acting, so the "stream" is held up. I don't really have time for more writing for the evening, though, but good look in your quest. –  Daniel Andersson Mar 29 '12 at 18:17

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.