user2972122
user2972122

Reputation: 161

How to assign a boolean expression condition to a variable in shell

I wanted to do the following in shell script.

Assign a variable CON_1 based on no. of arguments passed, later i will use this CON_1 variable in another if condition

if [ $# < 2 ];then
CON_1=([ $m = Online ])
else
CON_1=[ $m = Online -a ${#bld_stat} -gt 0 ]

Based on CON_1 variable value i'm printing a message

if $CON_1; then

I do not know whether this is possible in shell, if it is possible can someone please guide me on this.

Upvotes: 2

Views: 929

Answers (1)

choroba
choroba

Reputation: 241918

You can store a result in a variable easily:

[ $m = Online -a ${#bld_stat} -gt 0 ]
condition=$?

You can store the source of a condition in a variable, too, but then you need eval to run it:

condition='[ $m = Online -a ${#bld_stat} -gt 0 ]'
eval "$condition"

Without eval, variables wouldn't be expanded, as variable expansion happens only once.

Instead of a variable, use a function:

condition () {
    [ $m = Online -a ${#bld_stat} -gt 0 ]
}
if condition ; then ...

You can even pass arguments to functions:

condition () {
    [ $m = Online -a ${#bld_stat} -gt "$1" ]
}
if condition 12 ; then # Will use 12 instead of 0 to compare.

Upvotes: 5

Related Questions