Wednesday, April 5, 2017

Bash: Scripting - Lists symbolic links in directory

#!/bin/bash
# symlinks.sh: Lists symbolic links in directory.

directory=${1-$(pwd)}


# Defaults to current directory,
#+ if not otherwise specified
.
# Equivalent to code block below
#---------------------------------------------------------
# ARGS=1                # Expect one command-line argument
#
# if [ $# -ne "$ARGS" ] # If not 1 arg...
# then
#       directory=$(pwd)        # current working directory
# else
#       directory=$1
#fi
#---------------------------------------------------------
echo "Symbolic links in directory \"$directory\""
for file in "$(find $directory -maxdepth 1 -mindepth 1 -type l)" # -type l= symbolic links
do
        echo "$file"
done | sort





# Strictly speaking, a loop isn't really neccessary here,
#+ since the output of the "find" command is expanded into a single word.
# Howerver, it's easy to understand and illustrative this way.
# Failing to quote $(find $directory -type l)
#+ will choke on filenames with embedded whitespace.


exit 0





Results:
$ ./symlinks.sh /prd_webroot/docs
Symbolic links in directory "/prd_webroot/docs"
/prd_webroot/docs/catalog_server.pl
/prd_webroot/docs/Corp
/prd_webroot/docs/Dept
/prd_webroot/docs/Images

No comments:

Post a Comment