SNAPSHOT = $(SnapshotIR$TODAY*.csv)
You can't have a space in assignments. Furthermore, $(…)
is a command substitution: this line attempts to execute SnapshotIR02122013_2239.csv
as a program.
In bash, ksh or zsh, set SNAPSHOT
to be an array containing the list of matching file names.
SNAPSHOT=("SnapshotIR$TODAY"*.csv)
If there is no matching file, the pattern is left unexpanded. In bash or zsh, set the nullglob
option to get an empty array instead. In ksh, put ~(N)
at the beginning of the pattern (i.e. SNAPSHOT=(~(N)"SnapshotIR$TODAY"*.csv)
). You can then test if there were any matching files by testing the length of the array.
shopt -s nullglob
SNAPSHOT=("SnapshotIR$TODAY"*.csv)
if [ ${#SNAPSHOT} -eq 0 ]; then
echo 1>&2 "No snapshot file for $TODAY"
exit 2
elif [ ${#SNAPSHOT} -gt 1 ]; then
echo 1>&2 "Multiple snapshot files for $TODAY, I don't know which one to pick"
exit 2
fi
echo "The snapshot file is ${SNAPSHOT[0]}"
In shells without arrays, you can use a function that receives the list of matches and counts them. If there is no match, the function receives the pattern unexpanded.
set_snapshot () {
if [ $# -gt 1 ]; then
echo 1>&2 "Multiple snapshot files for $TODAY, I don't know which one to pick"
exit 2
elif [ -e "$1" ]; then
SNAPSHOT=$1
else
echo 1>&2 "No snapshot file for $TODAY"
exit 2
fi
}
set_snapshot "SnapshotIR$TODAY"*.csv
echo "The snapshot file is $SNAPSHOT"
(Note that using [ -e "$1" ]
to test whether the pattern was left unexpanded fails in pathological cases such as [0-9]
when there is no file whose name is a single digit but there is a file with the 5-character name [0-9]
. This can't happen with only *
or ?
metacharacters since they match themselves.)
The following approach works to some extent:
SNAPSHOT=SnapshotIR$TODAY"*.csv
if [ -e $SNAPSHOT ]; then …
Since the expansion $SNAPSHOT
is left unquoted, it is treated as a whitespace-separated list of wildcard patterns, which is ok here. However, if there is more than one matching file, the matches will be seen as separate arguments by the [
command, and that will cause a syntax error. (With specially-crafted file names, it could even cause a wrong result.) So I don't recommend this approach, it's too brittle.