Page 1 of 1

CGI Bash script

Posted: Fri Jun 08, 2018 11:30 am
by fredella
Hello, I'm writing a Cgi script that generate a html page that run on Apache server.
I want redirect the browser to a page if some parameters is not present in the url.

Code: Select all

#!/bin/bash
PARAMS=`echo $QUERY_STRING | cut -d\? -f 2`
.....
ACT1=`echo $PARAMS | cut -d\& -f 1`
ACT2=`echo $PARAMS | cut -d\& -f 2`
ACT3=`echo $PARAMS | cut -d\& -f 3`
.....
echo "<head>"
if[($ACT1 != "IN1=on" && $ACT1 != "IN1=off")||($ACT2 != "IN2=on" && $ACT2 != "IN2=off")];
then
    echo "<meta http-equiv=\"refresh\" content=\"1;URL='/GPIO_GETDIR.php'\"/>"
fi
Why this if statement does not work?

Thank You

Re: CGI Bash script

Posted: Fri Jun 08, 2018 11:51 am
by fredella
The error is:

./ciao.cgi: line 103: if[[( != IN1=on && != IN1=off)||( != IN2=on && != IN2=off)]]: command not found

Re: CGI Bash script

Posted: Fri Jun 08, 2018 11:55 am
by tpyo kingg
One problem would be the 'if' running up against the test [ there should be white space after the 'if' command. And then each test needs to be done separately. See "man test" or "man ["

Code: Select all

if [ $ACT1 != "IN1=on" ] && [ $ACT1 != "IN1=off" ] \
    || [ $ACT2 != "IN2=on" ] && [ $ACT2 != "IN2=off" ];
then
    echo "<meta http-equiv=\"refresh\" content=\"1;URL='/GPIO_GETDIR.php'\"/>"
fi
Keep in mind the order of precedence with || and && also.

Re: CGI Bash script

Posted: Fri Jun 08, 2018 2:50 pm
by fredella
Thank You, the code now works with following lines:

Code: Select all

if  [ $ACT1 == "IN1=on" ] || [ $ACT1 == "IN1=off" ] 
then
    if  [ $ACT2 == "IN2=on" ] || [ $ACT2 == "IN2=off" ] 
    then
        echo "Param OK"
    else
        echo "<meta http-equiv=\"refresh\" content=\"1;URL='/GPIO_GETDIR.php'\"/>"
    fi
else
    echo "<meta http-equiv=\"refresh\" content=\"1;URL='/GPIO_GETDIR.php'\"/>"
fi
Is there a way to use something like this to obtain the same result of previous code?

Code: Select all

if [ [ $ACT1 == "IN1=on" ] || [ $ACT1 == "IN1=off" ] ] && [ [ $ACT2 == "IN2=on" ] || [ $ACT2 == "IN2=off" ] ]
then
    echo "<meta http-equiv=\"refresh\" content=\"1;URL='/GPIO_GETDIR.php'\"/>"
fi

Re: CGI Bash script

Posted: Fri Jun 08, 2018 5:11 pm
by tpyo kingg
I would think that the following would work.

Code: Select all

if ( [ $ACT1 = "IN1=on" ] || [ $ACT1 = "IN1=off" ] ) && ( [ $ACT2 = "IN2=on" ] || [ $ACT2 = "IN2=off" ] );
then 
    echo OK;
else
    echo NOT OK; 
fi
Try the manual page for bash and check the sections on conditional commands and compound commands to be sure.

Re: CGI Bash script

Posted: Sat Jun 09, 2018 12:41 pm
by pksato
Hi,
quote the testing string variable.

Code: Select all

if [ [ "$ACT1" != "IN1=on" -a "$ACT1" != "IN1=off"] -o [$ACT2 != "IN2=on" && $ACT2 != "IN2=off"] ];
These conditional are correct?

If have a php, why cgi using bash?
Use php popen() to call you script or other executable. Or proc_open().