I did put this line shopt -s expand_aliases; alias ln=ln_s in script1.sh but the output shows that that it is still picking ln instead of ln_s .
Output:
Please consider calling a second script i.e script2.sh from the first i.e script1.sh while having the command set in script2.sh while the alias set in script1.sh in your test.
Also find the details below.
bash-4.1$ bash --version
GNU bash, version 4.1.17(1)-release (sparc-sun-solaris2.11)
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
bash-4.1$ uname -a
SunOS mymac 5.11 11.2 sun4v sparc sun4v
In Post# 9 i have shown that the function ln_s() is define in script1.sh.
I am sourcing script2.sh inside script1.sh here -> source ~/script2.sh and then i am executing script2.sh from within script1.sh here -> ~/script2.sh with the expectation that the ln command in script2.sh should be executed as ln_s thus calling the function.
OK, very good, the alias should be known, but not the function
Why this second execution? And, neither alias nor function will be available
No, as explained.
Let me comment on your script snippet:
shopt -s expand_aliases; # setting the necessary shell option
alias ln=ln_s # defining the alias IN THE CURRENT ENVIRONMENT in which the function IS NOT KNOWN YET
echo "Starting Execution"
source ~/script2.sh # sourcing (=reading & executing) the script IN THE CURRENT ENVIRONMENT; alias known, function not known
~/script2.sh # running the script (again!) in a NEW subshell IN A NEW ENVIRONMENT; alias not known, function not known
echo "End of Execution"
ln_s() # defining the function for LATER USE!
{
[[ -e $2 ]] && return
ln -s "$1" "$2"
}
. # from here on, ln will correctly call the function
.
.
I strongly recommend you get your head around shells and subshells, the difference between sourcing a collection of commands and executing them in a subshell, environment inheritance, and function definition.