I’m making this tiny program in Shell:
#***************************************************************
# Function.
# NAME: chk_df
# Synopsis:
# Check if a local directory (dirName) exist and has a file (fileName).
#
#
# The return codes are the following:
# 99 : dirName does not exists
# 0 : dirName exists and has fileName
# 1 : dirName exists and has not fileName
#
# Parameters:
# In values: dirName <string> fileName <string>
# Out values: returnCode <int>
#
# How to use:
# chk_df dirName fileName
#***************************************************************
chk_df(){
# Check the number of arguments that could be passed.
# In this case, two, dirName, fileNAme.
if [[ ${#@} != 2 ]]; then
echo "Error ...Use [Function]: chk_df <dirName> <fileName>"
echo "Ex: chk_df /foo lola.txt"
exit
fi
DIR=$1
FILE=$2
[[ ! -d $DIR ]] && return 99
[[ -d $DIR && ! -e $DIR/$FILE ]] && return 1
[[ -d $DIR && -e $DIR/$FILE ]] && return 0
}
Because I need to check if a file is in a directory, I did this (horrible?) patch $DIR/$FILE , but things like this could happen:
I) If we do: chk_df /foo lola.txt
We get: /foo/lola.txt
II) If we do: chk_df /foo/ lola.txt
We get: /foo//lola.txt [Notice the //]
In both cases the code seems to work. Why? I read that backslash acts like a space. So, could I put n backslash without unknown problems?
Could I leave it like that or it will bring problems? Is there a difference? UNIX assume it to the right way?
EXTRA QUESTION: why I can not do the returns with negative numbers? This is: return -1
/,//, or any string of consecutive slashes have the same meaning according to the POSIX standard, with the exception that they may have a different meaning at the beginning of a path (so/fooand//foomay denote different objects). Linux does not use this exception, so any number of consecutive slashes always means the same thing as a single/.(The exception is there to cater to the needs of other Unix-like systems that use leading
//to denote a network path.)