KSH: Import File With Variables and Functions

How do I import variables and functions defined in lib.ksh script to another ksh script called setup.ksh under Linux / Unix like operating systems? How do I execute commands from a file in the current KSH shell?

To read and execute commands from given FILENAME in the current shell use the following syntax:

. /path/to/file

OR

. /path/to/lib.ksh

The . (dot) is one of the KSH built-in commands. You can also use an alias called source as follows:

source /path/to/lib.ksh

Example

Create a script called /tmp/lib.ksh as follows:

#!/bin/ksh
# defaul values ##
vech="Bus"
rent=14
type="A/C"
 
 
# Display info
function showvech {
  printf "Vehicle: %s\n" $vech
  printf "Type (ac or non-ac): %s\n" $type
  printf "Rent (per/km): Rs.%d km\n" $rent
}
 
# Set info
function setvech {
  vech="$1"
  rent=$2
  type="$3"
}

Create a script called test.ksh:

#!/bin/ksh
 
# source our /tmp/lib.ksh
 
. /tmp/lib.ksh
 
# show defaults
showvech
 
# set new values and display it back
setvech "Jeep" 9 "Non-A/C"
showvech

Sample outputs:

Vehicle: Bus
Type (ac or non-ac): A/C
Rent (per/km): Rs.14 km
Vehicle: Jeep
Type (ac or non-ac): Non-A/C
Rent (per/km): Rs.9 km

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 0 comments... add one


CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
0 comments… add one

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum