简体   繁体   中英

How to Access a variable in a Shell script

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?

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 .

From what I understand, you want to get the variables from settings , use $role as an indirect reference to $admin , ie 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM