title: Get grandparent directory in bash script - rename files for a directory in their paths
body: <p>I have the following script, which I normally use when I get a bunch of files that need to be renamed to the directory name which contains them.</p>
  
  <p>The problem now is I need to rename the file to the directory two levels up.  How can I get the grandparent directory to make this work? </p>
  
  <p>With the following I get errors like this example:
  "mv: cannot move <code>./48711/zoom/zoom.jpg</code> to <code>./48711/zoom/./48711/zoom.jpg</code>: No such file or directory".  This is running on CentOS 5.6.</p>
  
  <p>I want the final file to be named: 48711.jpg</p>
  
  <pre><code>#!/bin/bash
  
  function dirnametofilename() {
    for f in $*; do
      bn=$(basename "$f")
      ext="${bn##*.}"
      filepath=$(dirname "$f")
      dirname=$(basename "$filepath")
      mv "$f" "$filepath/$dirname.$ext"
    done
  }
  
  export -f dirnametofilename
  
  find . -name "*.jpg" -exec bash -c 'dirnametofilename "{}"'  \;
  
  find .
  </code></pre>