|-常见问题
        |-详细问题
MANIPULATE FILENAMES WITH EASE
MANIPULATE FILENAMES WITH EASE

When you're dealing with files, it's often convenient to manipulate
filenames. For instance, if you wrote a script and wanted to display a single
filename, but the input was the full path and filename, you could use a
little sed magic to obtain the file's actual name. However, this is
inconvenient. There are commands available that you can use, which allow you
to avoid using complex regular expressions and sed or awk syntax to
accomplish this.

Take the file /usr/local/bin/bashscript.sh, for example. If you wanted
to obtain just the filename, you could use something similar to:

# basename /usr/local/bin/bashscript.sh

The value returned would simply be bashscript.sh. This becomes handy
when you're using a script and want to print a help screen for the user. For
example:

BASENAME=`basename $0`
....
echo "Usage: $BASENAME -args -options"
....

Similarly, you can use the dirname command to obtain the full path for a
file or directory. For instance, suppose you wanted to obtain the
directory in which bashscript.sh is located. You could execute: # dirname
/usr/local/bin/bashscript.sh; dirname would return "/usr/local/bin". If you
used dirname against a directory and not a file (e.g., # dirname
/usr/local/tmp123), dirname would return the full path above the specified
directory; in this case, it would return "/usr/local".

The ability to use basename and dirname is useful when writing shell
scripts. Without knowing either command, you might, instead, use awkward sed
syntax to obtain the same information that you can find using these
simple commands.