firasKoubaa
firasKoubaa

Reputation: 6867

Shell how to assign a result of string test in a variable

I ve a shell script :

#!/bin/bash
server=$1
modules=$2
is_selected= if [[ $modules== *"myModule"* ]]; then true else false fi

I want that if the condition $modules== *"myModule"* is verified ,

then the variable is_selected gets true , else false

How may i adjust it in one line ?

Upvotes: 0

Views: 52

Answers (2)

chepner
chepner

Reputation: 531948

You need command substitution, and you command has to output the string true or false.

is_selected=$( if [[ $modules == *"myModule"*; then echo true; else echo false; fi)

Or put the assignment in the if statement:

if [[ $modules == *myModule* ]]; then is_selected=true; else is_selected=false; fi

which has the benefit of not requiring a subshell (and likely a new process) for the command substitution.

Or using a suggestion from the comments, initialize the variable to false, then set it to true if the match succeeds.

is_selected=false; [[ $modules == *myModule* ]] && is_selected=true

Upvotes: 1

Poshi
Poshi

Reputation: 5762

Run a command substitution and echo the desired result:

is_selected=$(if [[ "$modules" == *"myModule"* ]]; then echo true; else echo false; fi)

Upvotes: 0

Related Questions