I am trying to run an if statement on a exiftool variable set in a bash script.
Looking to trigger an action if the ProductVersion returns a particular version.
I get the below error when running the bash script
sh testing.sh
testing.sh: 4: [: exiftool: unexpected operator
Below is the script I am attempting to run:
#!/bin/bash
ExifCommand="exiftool -ProductVersion /serverdata/serverfiles/test/Server.exe"
if [ $ExifCommand =~ *3.7* ]; then
echo "testing success"
fi
Another thing to note, if I put the command in ExifCommand=$(exiftool -ProductVersion /serverdata/serverfiles/test/Server.exe)
I get the below error:
testing.sh: 3: Product: not found
From comments:
how do I go about putting the output of that command into its own variable
The way to capture the standard output of a command is to use a command substitution, which you already demonstrate in the question:
$(some command)
. That can be protected against word splitting by double-quoting it, and the result assigned to a variable if that's what you want. For example:
ExifOutput="$(exiftool -ProductVersion /serverdata/serverfiles/test/Server.exe)"
You show a similar attempt in the question, which could well have been foiled by the absence of quotation marks.
The old-school / POSIX way of testing for a substring in that would be via a case
statement:
case ${ExifOutput} in
*3.7*) echo "testing success" ;;
esac
Note that there, the *3.7*
is a glob pattern, not a regular expression.
There is a bash-specific alternative involving its internal conditional-evaluation command, [[
, and a regular-expression matching operator =~
. That could be spelled like so:
if [[ "$ExifOutput" =~ .*3[.]7.* ]]; then
echo "testing success"
fi
Note well that pathname expansion is not performed on the arguments of [[
, else the regular expression would need to be quoted. Note also that it is a bona fide regular expression (POSIX flavor), not a glob pattern.