maurice
maurice

Reputation: 19

function doesn't work in script shell

I'm learning scripting shell in Linux. And now I have some problems with the creation of a function. I'm working on CentOS.

This is the function's code:

#votolaurea.lib
votolaurea() {
voto=$(($voto * 11))
voto=$((voto /3))
echo "Il voto sarà $voto";
}

And this is the script who call that function

#!/bin/bash
~/imieiscript/votolaurea.lib
echo "Give me the number"
read media
echo 'votolaurea.lib $media'

But the output is:

Give me the number
3 //this is my number in input
votolaurea.lib $media

It doesn't call the function but it prints all the command. Why?

Upvotes: 1

Views: 2110

Answers (2)

davidedb
davidedb

Reputation: 876

If I interpreted correctly your code, you created two files:

  • one named votolaurea.lib, containing the function votolaurea;
  • the other one unspecified (let's call it test.sh).

Remember that:

  • in order to use inside test.sh any function (or other definitions) present in votolaurea.lib, you need to source it using the source command (or its equivalent .);
  • single-quoted strings are not processed by the shell but are left unchanged; therefore if you want to call function votolaurea() you have to put it outside of the quoted string;
  • parameters are passed to functions using the positional parameters $1, $2, etc.

Taking into account of the previous points, you should apply some changes to your code.

votolaurea.lib

#votolaurea.lib
votolaurea() {
    echo $(($1 * 11 / 3 ))
}

test.sh

#!/bin/bash
source ~/imieiscript/votolaurea.lib
echo "Give me the number"
read media
echo "Il voto sarà $(votolaurea $media)";

Upvotes: 3

Dmitry Grigoryev
Dmitry Grigoryev

Reputation: 3203

To execute a string as a command, you should use `` or $():

echo `votolaurea.lib $media`
echo $(votolaurea.lib $media)

Upvotes: 0

Related Questions