1

I am attempting to simplify repetitive work procedures. In doing so, I am trying to write a .bashrc script which will set global path variables that aliases can refer to. Disclaimer: I'm new to linux and scripting in general so I don't know if the approach I've taken to this point is correct.

Here is what I've written so far.

SET_DIR=/var/www/

#Set the current site's root directory
function sroot (){
    SET_DIR=/var/www/$1
    setaliases
    echo $SET_DIR
}

#Reinitialize aliases with new sroot
function setaliases(){
    alias chk="echo $SET_DIR"
    alias rt="cd $SET_DIR"
    alias thm="cd $SET_DIR/sites/all/themes/"
    alias mod="cd $SET_DIR/sites/all/modules"
}

setaliases

What I would like to do is expand this Idea to define sites in an array or a file. Then use a function that will check the value passed to the sroot function. This will in turn set variables in other functions.

#myfile or array
site=example1.com
theme=alpha
shortcut=x1 

site=example2.com
theme=beta
shortcut=x2

So for example "sroot x1" would affect

SET_DIR=/var/www/$site
# and
alias thm="cd $SET_DIR/sites/all/themes/$theme"

How do I configure the function to check for a value in an array then use it's variables?

1

When you write:

alias thm="cd $SET_DIR/sites/all/themes/"

you're expanding the value of SET_DIR at the time you define the alias. That means you get the same value every time you run the alias, even if you've changed the variable value in between. If you backslash-escape the $ then the variable will be dereferenced when you use the alias instead:

$ foo=hello
$ alias test="echo \$foo"
$ test
hello
$ foo=world
$ test
world

So if you define the aliases in this way then you don't ever need to redefine them when you change SET_DIR. You can also single-quote the alias definition.

For your data file, Bash 4 and up supports associative arrays, which would let you define your data like this:

declare -A theme site # This makes these variables associative arrays
add_site() {
    local shortcut=$1
    theme[$shortcut]=$2
    site[$shortcut]=$3
}
add_site x1 example1.com alpha
add_site x2 example2.com beta

You could then access the values with e.g. ${theme[x1]}. Your aliases could then take the form:

alias thm="cd /var/www/\${site[\$CURRENT]}/sites/all/themes/\${themes[\$CURRENT]}"

Your sroot function would then just set CURRENT to the key you wanted. The alias would always take you to the right directory within the current site.

There are other approaches to defining the arrays in particular, but this will give you the general idea.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.