Hi,
Is there a special positional variables for when using the dot (.)?
Scripts are as below:
$: head -100 x.ksh /tmp/y.ksh
==> x.ksh <==
#!/bin/ksh
#
. /tmp/y.ksh 1234 abcd
echo "yvar1 = $yvar1"
echo "yvar2 = $yvar2"
==> /tmp/y.ksh <==
#!/bin/ksh
#
echo
echo "======================================"
echo
echo "\$* = $*"
echo "\$@ = $@"
echo
echo "======================================"
echo
echo "\$0 = $0"
echo "\$1 = $1"
echo "\$2 = $2"
echo
#export yvar1="YVAR_1"
#export yvar2="YVAR_2"
yvar1="YVAR_1"
yvar2="YVAR_2"
Sample run below:
$: ./x.ksh
======================================
$* = 1234 abcd
$@ = 1234 abcd
======================================
$0 = ./x.ksh
$1 = 1234
$2 = abcd
yvar1 = YVAR_1
yvar2 = YVAR_2
I am expecting /tmp/y.ksh to print in $0 or $1 but it isn't. Is there a special variable for when calling another script using the dot (.)?
I am at a loss as to what you are trying to do.
IF you are sourcing a file, . /path/to/file
then that will execute inside the parent shell.
Variables will be passed at that position where the sourced file is...
A quick demo...
Sourced file:
#!/bin/sh
# Test file to be sourced.
MYVAR=$1
echo "Inside source file \${MYVAR} = ${MYVAR}"
AND parent file:
#!/bin/sh
# Parent test file...
# Sourced file in the same directory.
. ./source_file.sh 'UNIX'
echo "Sourced file \${MYVAR} = ${MYVAR}"
MYVAR="Bazza"
echo "Parent file \${MYVAR} = ${MYVAR}"
. ./source_file.sh 'LINUX'
echo "Sourced file \${MYVAR} = ${MYVAR}"
Results OSX 10.14.6, default shell terminal.
Last login: Wed Oct 9 14:38:32 on ttys000
AMIGA:amiga~> cd Desktop/Code/Shell
AMIGA:amiga~/Desktop/Code/Shell> chmod 755 parent_file.sh
AMIGA:amiga~/Desktop/Code/Shell> chmod 755 source_file.sh
AMIGA:amiga~/Desktop/Code/Shell> ./parent_file.sh
Inside source file ${MYVAR} = UNIX
Sourced file ${MYVAR} = UNIX
Parent file ${MYVAR} = Bazza
Inside source file ${MYVAR} = LINUX
Sourced file ${MYVAR} = LINUX
AMIGA:amiga~/Desktop/Code/Shell> _
There's not a standard, "compatible" way, but there's often a way to get it:
$ cat dot1.sh
#!/bin/bash
# dot1.sh
echo "$0 1=$1 2=$2 file=$file"
set | grep dot1
. ./dot2.sh a b
$ cat dot2.sh
echo "$0 1=$1 2=$2"
set | grep "dot2"
$ ./dot1.sh 1 2
./dot1.sh 1=1 2=2 file=
BASH_SOURCE=([0]="./dot1.sh")
_='./dot1.sh 1=1 2=2 file='
./dot1.sh 1=a 2=b
BASH_SOURCE=([0]="./dot2.sh" [1]="./dot1.sh")
$ sed -i 's/bash/ksh/' dot1.sh # replace bash with ksh
./dot1.sh 1=1 2=2 file=
_='./dot1.sh 1=1 2=2 file='
file=/home/tyler/code/sh/dot1.sh
./dot1.sh 1=a 2=b
file=/home/tyler/code/sh/dot2.sh
$
This 'file' isn't a real variable, unfortunately, just something to be snagged from set. I think BASH_SOURCE is a real array however.