4

gurus. I'm developing a bash script and learning about arrays in bash. I read a couple of howto about that but my head blew up. I used to program in php and bash is new and "rudimentary" for me.

I'm going to put multilang support to my script and I need to define all visible phrases in different arrays to get them calling a function with a parameter. Hard to explain I'll put what I want to do in php what is my "comfort" language and then my not working aproximation in bash script.

Php:
function english($index) {
    $strings=array(
                "phrase1",
                "phrase2"
                );
    return $strings[$index];
}
echo english(1); //It produces (zero based) "phrase2"

Ok, now my poor bash script trying to do the same:

Bash:
function english() {
    strings=("phrase1" "phrase2")
    return ${strings[$1]}
}
echo english 2

How can I return the desired value of array calling a function containing the array and based on the function parameter?

Anyone has a good bash manual to do some practices about this? Thank you.

1
  • bash functions returns int as status values, not Strings. Commented Mar 7, 2016 at 21:07

2 Answers 2

2

Return values in shell are for exit codes, not data. Instead, write the value to standard output (and capture it with command substitution, if necessary).

english () {
    strings=("phrase1" "phrase2")
    echo "${strings[$1]}"
}

english 1          # Arrays are indexed from 0
word=$(english 0)  # word=phrase1
Sign up to request clarification or add additional context in comments.

Comments

0

Try:

function english {
    strings=("phrase1" "phrase2") 
    echo ${strings[$1]}
}
#Arrays are zero-based
english 1;

Bash Guide for Beginners

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.