1

I tried 3 internet examples to write a bashe shell function and call it via my xterm terminal with no success.

1-my functions are saved in a file "example" and this file is inexecutable mode.

2-inside this example file i wrote:

 #!/bin/bash 
           function quit {
               exit
           }
           function hello {
               echo Hello!
           }

3- in xterm terminal, in the folder that this file is located i called these two functions in these ways:

$./quit     $./hello    

and in this way:

$quit     $hello

none of them work.but if i change the following function to a script (without function word) and call the FILE, it works.

Any idea, what is going on?

Thanks

4 Answers 4

3

You need to source your script to load function definitions to current shell environment:

# source script
. example

# call function
hello

# call function
quit
Sign up to request clarification or add additional context in comments.

Comments

1

You need to make the function definitions available to the outside shell. For this, you need to source the example file:

. example
quit
hello

You can also do source example.

Comments

1

Once you've written the functions, they only visible inside the script file itself. For them to be visible outside it, you need to tell the script to export the functions to the environment.

Try adding export -f quit and export -f hello after your function definitions.

Let's clear up confusion with the ./ and $ operators.

The first operator ./ is used when you want to call a script in the current directory. For example, if you've defined your script in some file script.sh, then you could call it with ./script.sh (make sure you have execute permissions - you can add them with chmod +x script.sh).

The second operator $ is used to look at environment variables. These are variables which are defined by default in the bash shell, or variables which you have defined and exported to the shell. Try entering the following into your shell.

pi=3.14
echo $pi
3.14

Here, the $ prefix allows you to access the variable you created.

Comments

0

./quit Or ./hello means that you have files named quit and hello and you want to execute them. and $quit and $hello means that quit and hello are predefined commands (executable files in $PATH folders e.g /usr/bin) when you define a function in shell file, you should use it in that file too!

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.