Reputation: 5714
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.
Upvotes: 4
Views: 435
Reputation: 1254
Try:
function english {
strings=("phrase1" "phrase2")
echo ${strings[$1]}
}
#Arrays are zero-based
english 1;
Upvotes: 0
Reputation: 530950
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
Upvotes: 2