Bash v/s Cshell - Functions and their definitions - useful 'type' keyword

Hey if you have worked on Linux then you have interacted with bash. Maybe not. But it is mostly likely that your default shell is bash. I'm not surprised. I'm among the few people on this planet who regularly interacts with cshell also. Thanks to the kind of work I do.
One great feature of bash that I miss in cshell is: Functions.
Surprised? Cshell doesn't support functions. It doesn't have any concept of function. If you wanted to simulate a function, you have to write another cshell script that does what your function would do and define an alias that calls it.

Let us look at an example of a sort of function in C-shell The code below is our testHelloWorld.csh script.

1#! csh  
2alias helloWorld = 'csh /home/user/username/helloWorld.csh'  

Now write the helloWorld.csh script like below:

1#! csh  
2echo "Hello World!!"  

Now in your command line if you run the testHelloWorld.csh you would get what you need. That would have been so much easier in bash. Because you have functions. You can write all the code that are logically related to each other in one script as different functions and then invoke them whenever you need. As long as the function is defined and exported, other scripts would also be able to use it.
Functions are defined in bash using the function keyword. Let us take a look at an example function definition in a script called

1#! bash  
2function helloWorld(){  
3    echo "Hello World!!"  

Now that you could run the script using :

1prompt : sh  

Now if you wanted to make that function available for other scripts, then you would write a function definition and then use the export keyword to export the function definition to the outside world.

1function helloWorld(){  
2    echo "Hello World!!"  
4export -f helloWorld  

Now if i were to run the above script using the source command then I would have the function definition exported to other scripts. So now if I typed helloWorld, it would display the greeting.
What if you were looking at some code and you saw a command named commando in it? Not that I would name my function like that. But if you had a colleague who was crazy about commandos. How would you figure out what commando did?
Bash has a keyword for that as well. type. If I were you I would ask your crazy colleague what that command did. But if he or she is not around, you could use the keyword I just told you. And it would display what that command was and if it was a function it would show you the definition.``` egopalakrish@mysystem : type commando
commando is a function
commando ()
perl /home/user/username/ "$@"

comments powered by Disqus