Shell - references and dynamic variables

I learned the past week that shell programming with all its pitfalls can be quite once things are worked around. Now this is partially unfair - the shell has been told "run that old dusty code, and advance too"

So there are the original [] tests, then came [[ ]] tests, and then more neat functionality with the math engine (( ))

Ruby, Perl - they get to rev versions. The shell is not allowed to, sort of. So it seems the functionality was added in, via new testing.

How else would you upgrade a language where one of the rules was "can't alter existing behavior".

If anything, this helped me not get all frustrated there are 3 types of bracket/brace tests...

Being Perl is my most comfortable language to code in, I had to find the shell equivs..

Regex checks

if ( $var =~ /[0-9][a-z]/) {
    printf STDERR "message\n";
}

:::shell
if [[ $var =~ [0-9][a-z] ]]
then
    print -u2 "message\n";
}

There are plent of guides to show the various tests. What I like today was figuring this out

% cat dyn.ksh
#!/bin/ksh

function makeVar {
    vname=$1
    eval "$1=$2"
    rc=$?
    return $rc
}

makeVar answer 42
print -u2 "the var 'answer' was eval'd and \"answer\" has a value of \"$answer\""

typeset -n c2=answer
print -u2 "the variable c2 was  typeset -n c2=answer   (copy reference) and c2 has a value of \"$c2\""

And running it yields that dynamic vars can be made.

% ./dyn.ksh
the var 'answer' was eval'd and "answer" has a value of "42"
the variable c2 was  typeset -n c2=answer   (copy reference) and c2 has a value of "42"

Published on in