Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I am using rhel 5. I am learning shell-scripting.I created a function named

vi /etc/bashrc (so that i can use this function even after logout)

currenttime()
{
echo -e "Current time is `date`";
echo -e "Calendar Of this month is `cal`";
echo -e "Good Bye Mr.$USER ..Have good day";
}

Now if i use this function as normal then there is no problem. But when I am using this function under a script file and try to execute that script. Now it is showing error currenttime command not found

Vi my_script

currenttime 

chmod +x my_script
sh my_script
currenttime command not found.

Now i am not able to understand if currenttime is working properly in normal manner like #currenttime -----working fine

But, if i use it in file it is showing error. Can you tell me the logic behind this.

share|improve this question

2 Answers 2

You have to load /etc/bashrc in your custom script, since this file and ~/.bashrc is only loaded for interactive shells.

#!/bin/bash
source /etc/bashrc
currenttime
share|improve this answer

@above

You are right sir..i got some more expalination.it is like as

You can use your function when you're using an interactive shell (ie, when you're working on CLI). That's because /etc/bashrc it's sourced by all interactive shells on startup (if your distro was configured that way, of course).

But you can't use the same function on your scripts. And that's because your scripts doesn't know anything about your function. /etc/bashrc it's used only for interactive shells, not non-interactive shells (ie, subshells spawned for script execution).

You have to source /etc/bashrc manually, or include the function code on your scripts, or write down the function code on another script, which can after be sourced by the other scripts.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.