I want to just comment on the most important part:
if($category = $request)
A shell if
works another way, which is by running a command and using its return code.
An example is:
if /usr/bin/somecommand; then
echo "somecommand exited with exit code 0 (success)"
fi
to compare two strings, you would use
if /bin/test a = b; then
echo "a=b"
fi
Note that test
may be a builtin in your shell, but you usually have it as binary as well.
The next thing is, that you usually have a symlink from /bin/[
to /bin/test
. This means you can do:
if [ a = b ]; then
echo "a=b"
fi
where [ a = b ]
is the same as test a = b
and the trailing ]
is just there for a nicer syntax.
This is the reason, why if [a=b]
won't work, as the syntax above means [ "a" "b" "]"
, where [
is a program name. Without the space, the shell is looking for [a=b]
.
Your syntax using (a = b)
uses a subshell to run the command inside, resulting in a command a = b
, where a is considered to be a program name.
Another possible pitfall of your code is, that variables may be empty. Have a look at this code:
b=something
if [ $a = $b ]; then
echo $a = $b
fi
This will give an error, because it is equivalent to test = something
(running test "=" "something"
). The echo
below has a similar problem, but for echo this does not matter very much. The way to fix this is using appropriate quotes:
b=something
if [ "$a" = "$b" ]; then
echo "$a = $b"
fi
Resulting in the test command line: test "" "=" "something"
, which is a correct command. I fixed potential problems on the echo line by putting the whole string into quotes, which make them one single parameter for the echo command (or builtin).