View Full Version : BASH: Passing result of boolean expression to a function
demonGeek
January 11th, 2010, 12:24 AM
I'd like to evaluate a boolean expression and pass the result as a parameter to a function. Here's the code I have so far:
dayOfMonth=$( (date +%-d) )
[ $dayOfMonth = 10 ]
MyFunction "$?"The code above works but I'd really like to combine the boolean expression and the function call into a single line so that it looks something like this (which doesn't work):
MyFunction "[ $dayOfMonth = 10 ]"Any help would be appreciated.
- Adam
croto
January 11th, 2010, 01:18 AM
How about changing the double quotes by backticks?
MyFunction `[ $dayOfMonth = 10 ]`
EDIT: My suggestion does not work, you need the exit code, not stdout.
slakkie
January 11th, 2010, 01:29 AM
I don't think that is possible.
You could do it ala
bla=$( [ 0 -eq 0 ] ; echo $?)
your_func $bla
which would become:
your_func $([ 0 -eq 0 ] ; echo $?)
but that's the same as doing what you are currently doing. I would keep your current version.
jpkotta
January 11th, 2010, 01:34 AM
How about changing the double quotes by backticks?
MyFunction `[ $dayOfMonth = 10 ]`
EDIT: My suggestion does not work, you need the exit code, not stdout.
Return status of the last command is $?. Zero means OK/true/no error.
false ; echo $?
[ 0 = 0 ] ; echo $?
demonGeek
January 11th, 2010, 03:33 AM
Thanks for the help everyone.
Slakkie: Your suggestion worked out for me - it's ugly but it does the job:
dayOfMonth=$( (date +%-d) )
MyFunction "$([ $dayOfMonth = 10 ];echo $?)"
Powered by vBulletin® Version 4.2.2 Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.