I have a bash script that contains many common functions definitions for our Linux system.
Is it possible to source it and use functions from another shell flavor (csh and ksh) ?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
As Stéphane Chazelas noted in the comments,
csh and related
tcsh do not have functions, hence you can't source the functions file you have anyway.
However, bourne-like shells often share syntax and functionality, and in fact
bash borrowed a lot of functionality from
ksh, but some of the features these shells have aren't compatible with
dash - a default shell on Ubuntu and a closer one in behavior to original Bourne shell.
Another issue that comes up is not just about functions, but commands that functions might call. If you're using those functions on Ubuntu, and then suddenly go to FreeBSD, you'll quickly find out that utilities like
ps often have options that either behave differently or missing.
So in order to make sure you can use functions, I would suggest two things: consider commands and portability of their options and two - write functions that stick to POSIX standard and original Bourne shell syntax as close as possible.
Alternatively, if you have the luxury to always install the shell you want (which might not happen if you don't have
sudo privileges on the system you're working), then write your functions in one specific shell's syntax.
See When is it important to write portable scripts? for additional info.
In general, no.
tcsh) have a too different syntax from the
sh-derived shells (
zsh), so they would most likely not understand a
sh script, or vice versa.
sh shells can sometimes share functions or even whole scripts, but only if they are written for the "smallest common denominator shell", which is usually
sh. This, however, is usually not a good idea.
Think of each shell as a separate scripting language, like Perl, Ruby and Python. Don't mix them, and don't generally assume that one interpreter can understand the source of another.
In specific for the C Shell, you cannot, since C Shell doesn't support functions. Apart that, C Shell uses different syntax. For example, the following C Shell snippets are different from what Bash would use.
if ( $days > 365 ) then echo This is over a year. endif
set i = 2 set j = 1 while ( $j <= 10 ) echo '2 **' $j = $i @ i *= 2 @ j++ end