Exceuting function in Shell file from command

In my shellFile.sh I wrote this function:

#!/bin/bash
myFunction(){
echo 1
}

I tried to call the function from the command line this way:

shellFile.sh
shellFile.sh myFunction

After this two lines there is no output and no errors. I apologize if this question is asked before but I couldn't find it.

Upvotes: 0

Views: 62

Answers (4)

Cyrus
Cyrus

Reputation: 88979

I suggest:

#!/bin/bash
myFunction(){
  echo 1
}

$1

Usage: ./shellFile.sh myFunction

Output:

1

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 755054

If you want the function to be available from the command line, you need to create the function in the current shell, using the dot . command, or in Bash its workalike source:

$ . shellFile.sh
$ myFunction
1
$

Upvotes: 1

Barmar
Barmar

Reputation: 782653

You need to call the function in the script:

#!/bin/bash
myFunction() {
    echo 1
}
myFunction

Upvotes: 0

the_velour_fog
the_velour_fog

Reputation: 2184

you can call your function inside your script like this

#!/bin/bash
myFunction(){
echo 1
}

myFunction

If you want to use the function interactively you can source the script, then call the function from the command line.

$ source shellFile.sh
$ myFunction
1

Upvotes: 1

Related Questions