Check bash script variable against config file settings.

About writing shell scripts and making the most of your shell
Forum rules
Topics in this forum are automatically closed 6 months after creation.
Locked
JLC17
Level 3
Level 3
Posts: 175
Joined: Tue Feb 07, 2017 11:51 am

Check bash script variable against config file settings.

Post by JLC17 »

I'm trying to extend a script which is working fine as is, but can't make exceptions.

I'd like to be able to create a config file of the usual form:

[section]
key=value

and then be able to pull the keys and values into an array in bash so that I can have a line:

if ($myVar is in <array from file>) then ....

a lot of googling (and this forum) doesn't throw up a straightforward way, which must exist.

Could anyone help ?
Last edited by LockBot on Wed Dec 28, 2022 7:16 am, edited 1 time in total.
Reason: Topic automatically closed 6 months after creation. New replies are no longer allowed.
1000
Level 6
Level 6
Posts: 1039
Joined: Wed Jul 29, 2020 2:14 am

Re: Check bash script variable against config file settings.

Post by 1000 »

Does it look similar?
viewtopic.php?p=1950916&sid=d59d1be9a45 ... 5#p1950916

I can't help more because I don't see the script and I don't know where the problem is.

Edit.
Script can also be divided into two parts.
But this has its drawbacks

Code: Select all

RELATIVE_PATH_1="$(dirname "$(readlink -f "$0")")"
echo "$RELATIVE_PATH_1"
##  Load variables
. "$RELATIVE_PATH_1/config.sh"
https://www.linux.com/training-tutorial ... linuxunix/

And above relative path looks safer than relative path with dot " ./config.sh"
Why ?
If you will have in script " . ./config.sh "
And if you do

Code: Select all

cd ..
and you run script then you will see
./config.sh: There is no such file or directory
Last edited by 1000 on Tue Feb 02, 2021 1:36 pm, edited 1 time in total.
JLC17
Level 3
Level 3
Posts: 175
Joined: Tue Feb 07, 2017 11:51 am

Re: Check bash script variable against config file settings.

Post by JLC17 »

1000 wrote: Tue Feb 02, 2021 12:56 pm Does it look similar?
viewtopic.php?p=1950916&sid=d59d1be9a45 ... 5#p1950916

I can't help more because I don't see the script and I don't know where the problem is.
From first glance, no, but thanks.

I'm working to extend this script: viewtopic.php?t=302364 which as is just switches any connected BT device into a2dp mode. As I note on that thread, it's a little bit crude, as I have a headset I'd rather was in HFP mode.

So I thought if I have a .conf file: mydevices.conf, something like ..

Code: Select all

[Headsets]
mac1=HFP
mac2=a2dp
so that I can have a little bit of code that goes:

Code: Select all

		# search for connected device with AudioSink service
		if [[ `bt-device -i $mac | perl -00 -ne '/.*Trusted: 1.*\n\s*Blocked: 0.*\n\s*Connected: 1\n\s*UUIDs: .*AudioSink.*/ and print "1\n"'` ]]; then
			logger -p info "found mac: $mac"
  			# convert mac to pulse card name
    		pulsecard=`perl -pe 's/:/_/g' <<< "bluez_card.$mac"`

            if [[ $mac [b][i]is HFP[/i][/b] ]]; then
                enable_hfphsp
            else
	    		enable_a2dp
            fi
1000
Level 6
Level 6
Posts: 1039
Joined: Wed Jul 29, 2020 2:14 am

Re: Check bash script variable against config file settings.

Post by 1000 »

Termy example is very well ;-)

Example 1

Code: Select all

		if [[ `bt-device -i $mac | perl -00 -ne '/.*Trusted: 1.*\n\s*Blocked: 0.*\n\s*Connected: 1\n\s*UUIDs: .*AudioSink.*/ and print "1\n"'` ]]; then
			logger -p info "found mac: $mac"
            while read; do
                if [[ "$REPLY" == "$mac" ]]; then
                    PROFILE=$(cut -d"=" -f2 <<< "$REPLY")
                    case  $PROFILE  in
                    HFP)  
			            # convert mac to pulse card name
			            pulsecard=`perl -pe 's/:/_/g' <<< "bluez_card.$mac"`
			            # add something      
                    ;;
                    a2dp)
                        # convert mac to pulse card name
			            pulsecard=`perl -pe 's/:/_/g' <<< "bluez_card.$mac"`
			            enable_a2dp 
                    ;;
                    *)  
                        echo "Bad PROFILE = $PROFILE" 
                    ;;            
                    esac 
                    break
                fi
            done < file
		fi
Example 2

Code: Select all

		if [[ `bt-device -i $mac | perl -00 -ne '/.*Trusted: 1.*\n\s*Blocked: 0.*\n\s*Connected: 1\n\s*UUIDs: .*AudioSink.*/ and print "1\n"'` ]]; then
			logger -p info "found mac: $mac"
            PROFILE=$(grep "$mac" file | cut -d"=" -f2)
            case  $PROFILE  in
                HFP)  
			        # convert mac to pulse card name
			        pulsecard=`perl -pe 's/:/_/g' <<< "bluez_card.$mac"`
			        # add something      
                    ;;
                a2dp)
                    # convert mac to pulse card name
			        pulsecard=`perl -pe 's/:/_/g' <<< "bluez_card.$mac"`
			        enable_a2dp 
                    ;;
                *)  
                    echo "Bad PROFILE = $PROFILE" 
                    ;;            
          esac 
		fi
With Bluetooth commands / devices I can not help because I don't use and I don't know.
https://mobilityarena.com/bluetooth-pro ... avrcp-hfp/

Edit
From above

Code: Select all

 if ($myVar is in <array from file>) then ....

Code: Select all

if grep -q "$myVar" file ; then ...
Edit
I have doubts whether this is a good idea device recognition by mac. Maybe there is a better way?
User avatar
Termy
Level 12
Level 12
Posts: 4248
Joined: Mon Sep 04, 2017 8:49 pm
Location: UK
Contact:

Re: Check bash script variable against config file settings.

Post by Termy »

Damn, I think the only programs I have which use a configuration files are written in Perl. However, this is the sort of approach I'd take in BASH:

Code: Select all

#!/usr/bin/env bash

# You may want to include a method by which to reset the user's config, Such as
# by the user using a flag like `--force-reset` or `--reset-config`.
#
# You can make use of boolean True or False values, which are easy toggles for
# which to program, such as to enable or disable a feature. You could have a
# function like this:
#
#     BoolChk(){
#     	if [ "$1" != "$2" ]; then
#     		printf "ERROR: Invalid value for key '$1'." 1>&2
#     		exit 1
#     	fi
#     }
#
# Then you'd need only run something like:
#
#     BoolChk "$CurrentKey" "$CurrentValue"
#
# Where the variables are obviously applicable.

ConfigFile="$HOME/.config/test.cfg"

# To check the user doesn't use a bunch of nonsense.
ValidKeys=(
	'list'      # Description
	'of'        # of
	'valid'     # Each
	'keys'      # Key
)

# Create the configuration directory if it's not found. (parents, too)
[ -d "${ConfigFile%/*}" ] || mkdir -p "${ConfigFile%/*}"
#                 ^--          dirnames          --^

# I would add a timestamp and program version to the config file's header.
if ! [ -f "$ConfigFile" ]; then
	# Config file is generated here.
	while read; do
		printf '%s\n' "$REPLY"
	done <<-EOF 1> "$ConfigFile"
		# Example configuration file.

		list=Value1
		of=Value2
		valid=Value3
		keys=Value4
	EOF
	#   ^ Tabs are ignored in that here-doc. See bash(1) for more information.
else
	if ! [ -r "$ConfigFile" ]; then
		# I usually use an error function to make this cleaner & more concise.
		printf "ERROR: File '$ConfigFile' unreadable." 1>&2
		exit 1
	fi
fi

# Using an associative array. (A Key=Value system) Note that only unique keys
# can be stored in this array; check for duplicates by other means, if needed.
declare -A Keys
while read; do
	# Ignore comments, because of the header & user's own comments.
	[[ $REPLY == \#* || $REPLY == '' ]] && continue
	#                              ^-- Also ignore empty lines, in-case the
	#                                  user wants to organize their config.

	# Using Input Field Separator of '=', read the Key and Value, using
	# here-string. $REPLY expands to the entire line read by first `read`.
	IFS='=' read Key Value <<< "$REPLY"

	Keys[$Key]=$Value
done < "$ConfigFile"

#--------------------------------------------------Now Do Something with Values

for CurKey in "${!Keys[@]}"; {
	printf "Key '%s' is '%s'.\n" "$CurKey" "${Keys[$CurKey]}"
}
Actually forgot to incorporate the $ValidKeys array, but it's just gone 4am, so I'll leave that to your discretion.

BTW, the above is very efficient, in that it doesn't use any external programs except mkdir(1) from coreutils. Requires at least BASH 4, I believe, but pretty much everyone should have that at this point. :lol:
I'm also Terminalforlife on GitHub.
1000
Level 6
Level 6
Posts: 1039
Joined: Wed Jul 29, 2020 2:14 am

Re: Check bash script variable against config file settings.

Post by 1000 »

Do you seen this "Switch between HSP/HFP and A2DP setting" ?
https://wiki.archlinux.org/index.php/Bl ... DP_setting

Because I seen
But starting from Pulseaudio v. 11.0, it's possible to automatically switch the profile whenever microphone access is requested by the application, but it's disabled by default.
in https://askubuntu.com/questions/354383/ ... 06#1120106
Locked

Return to “Scripts & Bash”