Reputation: 11030
I'm currently stuck on how to do the following:
I have a settings
file that looks like this:
USER_ID=12
ROLE=admin
STARTED=10/20/2010
...
I need to access the role and map the role to one of the variables in the script below. After I will use that variable to call open a doc with the correct name.
test.sh
#!/bin/sh
ADMIN=master_doc
STAFF=staff_doc
GUEST=welcome_doc
echo "accessing role type"
cd /setting
#open `settings` file to access role?
#call correct service
#chmod 555 master_doc.service
Is there a way to interpolate strings using bash like there is in javascript? Also, I'm guessing I would need to traverse through the settings file to access role?
Upvotes: 0
Views: 6495
Reputation: 7253
I'd certainly use source(.)
#!/bin/sh
ADMIN=master_doc
STAFF=staff_doc
GUEST=welcome_doc
echo "accessing role type"
. /setting/settings 2> /dev/null || { echo 'Settings file not found!'; exit 1; }
role=${ROLE^^} # upercase rolename
echo ${!role}.service # test echo
Upvotes: 0
Reputation: 10103
With bash
and grep
and assuming that the settings
file has exactly one line beginning with ROLE=
:
#!/bin/bash
admin=master_doc
staff=staff_doc
guest=welcome_doc
cd /setting || exit
role=$(grep '^ROLE=' settings)
role=${role#*=}
echo chmod 555 "${!role}.service"
Drop the echo
after making sure it works as intended.
Look into Shell Parameter Expansion for indirect expansion
.
Upvotes: 5
Reputation: 32921
From what I understand, you want to get the variables from settings
, use $role
as an indirect reference to $admin
, i.e. master_doc
, then turn that into a string, master_doc.service
.
Firstly, instead of indirection, I recommend an associative array since it's cleaner.
You can use source
to get variables from another file, as well as functions and other stuff.
Lastly, to dereference a variable, you need to use the dollar sign, like $role
. Variable references are expanded inside double-quotes, so that's sort of the equivalent of string interpolation.
#!/bin/bash
# Associative array with doc names
declare -A docs=(
[admin]=master_doc
[staff]=staff_doc
[guest]=welcome_doc
)
echo "accessing role type"
cd setting || exit
source settings # Import variables
true "${ROLE?}" # Exit if unset
echo chmod 555 "${docs[$ROLE]}.service" # Select from associative array
# ^ Using "echo" to test. Remove if the script works properly.
Upvotes: 3
Reputation: 835
You can source the settings file to load the variables:
source settings
And then you can use them in your script:
chmod 555 "${admin}.service" # will replace ${admin} with master_doc
Upvotes: 0