View Full Version : [bash] test with a function
DLGandalf
October 26th, 2008, 05:59 PM
some pseudo code for a probably noob question, but in every tutorial they never test on functions
function x
{
return 0
}
if [x]; then
echo nice
else
echo bla
why does this give an command unknown error, as in it's trying to find a binary in my path instead of using the defined function.
wd5gnr
October 26th, 2008, 06:01 PM
Without thinking too hard... why not:
x
if [ $? ]
then ....
forger
October 26th, 2008, 06:10 PM
*spaces* *fi missing* *use $()* :)
$ function x { return 0; }
$ if [ $(x) ]; then echo nice; else echo bla; fi
nice
wd5gnr
October 26th, 2008, 06:49 PM
Actually I had thought of $() also and edited my post to add it (I thought I had tried it). But then I tried a little harder and removed it. Try this:
function x { return 1; }
function y { return 0; }
if [ $(x) ] ; then echo A ; else echo B ; fi
if [ $(y) ] ; then echo C ; else echo D ; fi
You get B and D!
skotos
October 26th, 2008, 07:19 PM
A full sample to try
#!/bin/bash
# GLOBAL CONSTANTS
declare -ir FALSE=1
declare -ir TRUE=0
# Functions
amIroot() {
local ROOT_UID=0;
if [ ${UID} -eq ${ROOT_UID} ]
then
return ${TRUE}
else
return ${FALSE}
fi
}
# Main
amIroot
nRC=$?
if [ ${nRC} -eq ${TRUE} ]; then
echo "`basename $0 .sh` is running with root privileges"
else
echo "root privileges required to run `basename $0 .sh`"
fiSave the code as test.sh and remember:
chmod +x test.sh
./test.shPay attention to equality: -eq is valid for numbers, = (just one) for strings.
The better way to compare strings is
if [ "X${CONST}" = "X${sVar}" ]; thenThe X's are wanted to avoid other errors.
DLGandalf
October 26th, 2008, 07:26 PM
why don't they add these helpful things in the dozen tutorials I've found
thanks for the replies!
agrings
January 31st, 2012, 07:10 PM
Maybe I'm a little late, but...
The problem here is the test function.
Remove it.
function x { return 1; }
function y { return 0; }
if $(x) ; then echo A ; else echo B; fi
if $(y) ; then echo C ; else echo D ; fi
sisco311
January 31st, 2012, 10:45 PM
Necromancy.
http://ompldr.org/tYzBtcQ (http://ompldr.org/vYzBtcQ)
Thread Closed.
Powered by vBulletin® Version 4.2.2 Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.