Sunday, April 28, 2024
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 2232  / 2 Years ago, wed, december 29, 2021, 11:14:23

I'd like to use variable as condition in case statement. Something similar to:



#!/bin/sh

ALLOWED_SERVICES=tomcat6|james;

case $1 in
$ALLOWED_SERVICES )
service $1 restart
;;
* )
echo "Unsupported argument"
;;
esac


This doesn't work. When script is started with tomcat6 argument for exapmle, it outpoots "Unsuported argument" message.
But when case condition is hardcoded it works ok:



case $1 in
tomcat6|james )
service $1 restart
;;
* )
echo "Unsupported argument"
;;
esac


Is it possible to use variables in this case?


More From » environment-variables

 Answers
7

Trouble is that both variable expansion and pattern expansion need to be done before matching and that doesn't work here. If you have a recent version of bash available you could use regex matching:



#!/bin/bash

ALLOWED_SERVICES="tomcat6|james"

if [[ $ALLOWED_SERVICES =~ $1 ]]; then
service $1 restart
else
echo "Unsupported argument"
fi


Add shopt -s nocasematch before the if to make the matching case insensitive.


[#35701] Friday, December 31, 2021, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
istmasted

Total Points: 287
Total Questions: 130
Total Answers: 153

Location: Burkina Faso
Member since Thu, Dec 23, 2021
2 Years ago
;