#!/bin/bash
# number of expected arguments
EXPECTED_ARGS=1
# exit value if the number of arguments is wrong
E_BADARGS=1
if [ $# -ne $EXPECTED_ARGS ]
then
echo "Usage: `basename $0` {arg}"
exit $E_BADARGS
fi
if [ ! -e $1 ]
then
echo "file $1 does not exist"
exit $E_BADARGS
fi
for myfile in $1/*
do
if [ -d "$myfile" ]
then
echo "$myfile (DIR)"
elif [ -f "$myfile" ]
then
echo "$myfile"
fi
done
I'm new to bash and I cannot figure out what !
means in if[ ! -e $1]
and what $1/*
means in for myfile in $1/*
. So far I've thought about if[! -e $1]
as if (not equal to first parameter) (do this).... is this correct? But then what is not equal to first parameter? for myfile in $1/*
, I've no idea what this means.
Any help?
if [ $# -ne $EXPECTED_ARGS ]
The -ne
operator tests if two numbers are "not equal." $#
is a variable representing the number of arguments passed. This line checks if it's different from the variable $EXPECTED_ARGS
.
if [ ! -e $1 ]
The -e
operator tests if a file exists on disk. $1
is a positional parameter, it's the first argument passed to the script. So this line is checking whether or not the file exists. See this page for more info on using if
in bash.
for myfile in $1/*
Expects that $1
is a directory, and goes through each file in the directory using globbing. Each file is loaded into the variable $myfile
.
There are a few issues with the script as is, as mentioned in the comments. I'd do things a little differently; see this as a first quick run at improving it: http://pastebin.com/4fbsdrDw
The !
means NOT, so if [ ! -e $1 ]
reads "if the first argument (of type file, directory or link) does not exist, do …" (the -e
is a file test operator of meaning "exists")
for myfile in $1/*
implies that your first argument is a directory and loops through all files in this directory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With