Em Ae
Em Ae

Reputation: 8704

Menu in shell script and then take the user input to do regex

never done shell script so seeking some guidance here. I have to write a script in which user would have list of options i.e.,

1. Upwork
2. Fiverr
3. FindAcoder

Now based on what user selects, I have to find configurations (which are stored in different file) for that option. The configurations are stored like this (can't change the format)

config file

<url_without_http>:<username>:<password>

The url_without_http will always have the string that is part of the menu (or i can change the menu to do so).

How can i create the menu, then take the put from uer in a variable and then use that variable to do a regex search in accounts.config file?

Upvotes: 0

Views: 149

Answers (2)

markp-fuso
markp-fuso

Reputation: 34474

Assuming the menu could have a variable list of items we can let select build the menu for us.

Sample data:

$ cat accounts.config
www.upwork.com:user1:password1
something.fIvErr.org:user22:password22

One idea using select:

$ cat menu.bash
#!/usr/bin/bash

menu_list='Upwork Fiverr FindACoder'
PS3='Select number: '                    # prompt displayed by 'select' command

select option in ${menu_list}
do
    break                                # we don't want an infinite loop that we need to ^C out of
done

echo "Menu number selected: ${REPLY}"
echo "Menu option selected: ${option}"

echo "++++++++++ matching config entry(s):"

grep -i "${option}" accounts.config

Sample runs:

$ menu.bash
1) Upwork
2) Fiverr
3) FindACoder
Select number: 1
Menu number selected: 1
Menu option selected: Upwork
++++++++++ matching config entry(s):
www.upwork.com:user1:password1

$ menu.bash
1) Upwork
2) Fiverr
3) FindACoder
Select number: 2
Menu number selected: 2
Menu option selected: Fiverr
++++++++++ matching config entry(s):
something.fIvErr.org:user22:password22

$ menu.bash
1) Upwork
2) Fiverr
3) FindACoder
Select number: 3
Menu number selected: 3
Menu option selected: FindACoder
++++++++++ matching config entry(s):

OP can add more code to address user picking a non-menu item (eg, 9), parsing the results from the grep, what to do if there's no match in the config file, etc.

Upvotes: 0

choroba
choroba

Reputation: 241898

Use select to create a simple menu in bash.

#! /bin/bash
config=/path/to/config.cfg

select keyword in $(cut -d: -f1 "$config") ; do
    if [[ $keyword ]] ; then
        line=$(grep "$keyword.*:.*:" "$config")
        break
    fi
done

url=${line%%:*}
passwd=${line##*:}
user=${line%:*}
user=${user#*:}

echo "URL:      $url"
echo "User:     $user"
echo "Password: $passwd"

Tested against:

google.com:googler:g00gle
youtube.com:youtuber:u2b
stackoverflow.com:developer:L337

Upvotes: 1

Related Questions