0

How to fill a case statement in a bash script, baised on the directories in a folder. So I have the following folder /opt/servers/ in this folder I have the following directories:
server1
server2
server3

Each of these directories equals a servername within Websphere Liberty.

How can I put those in a case statement?

I also want to use this script on multiple servers, and the serversnames are not the same, so I don't want to put the names of the servers hardcoded in the script. Because if an extra server will be added or removed I need to edit the script again an put that servername in there.

If I use the following, I get all the directories:

find /opt/servers/ -type d -name *server* | sort | awk -F'/' '{print $(NF-0)}'

But if I put the find in a variable and the echo it again, it print all the servers on one line:

SERVERS=`find /opt/wlp/ -type d -name *server*| sort | awk -F'/' '{print $(NF-0)}'`
echo $SERVERS
server1 server2 server3

How can I solve this? The goal is, that when a server is selected I get a new menu, where I can stop or start the server. So the script will do something like:

Hello please select one of the servers below:
1) server1
2) server2
3) server3

You have selected: server1
What do you want to do with this server?
1) stop
2) start

You have selected: stop
Are you sure?
1) Yes
2) No

You have selected: Yes
server1 will be stopped.
fabje
  • 31
  • 1
  • 7
  • Does this answer your question? [Losing newline after assigning grep result to a shell variable](https://stackoverflow.com/questions/754395/losing-newline-after-assigning-grep-result-to-a-shell-variable) – Alvaro Flaño Larrondo Jan 25 '22 at 12:05

1 Answers1

1

You can fill a bash array with the servers dirpaths and then use it to implement your logic:

#!/bin/bash

servers=( /opt/servers/*server* )

echo "Hello please select one of the servers below:"
select server in "${servers[@]##*/}"
do
    [[ $server ]] || continue
    echo "You have selected: $server"
    break
done

echo "What do you want to do with this server?"
select action in stop start
do
    [[ $action ]] || continue
    echo "You have selected: $action"
    break
done

# etc...
Fravadona
  • 5,892
  • 14
  • 26