sh脚本的行为取决于它的调用方式

时间:2015-05-14 14:49:58

标签: bash sh

A有一个简单的sh script1,可以调用更简单的script2。 如果我在bash shell中运行./script1./script1 1. script1. script1 1,我会得到四个不同的结果,其中包含script2参数的数量和值。

有人可以解释原因吗?

脚本是:

SCRIPT1

#!/bin/sh
sourceRc()
{
    echo "@script1: inside a fuction"
    . /home/user/test/script2 2
}
echo "@script1: # OF ARGUMENTS = "$#
sourceRc
echo "@script1: outside a fuction"
. /home/user/test/script2 2

SCRIPT2

echo "@script2: # OF ARGUMENTS = "$#
echo "@script2: ARGUMENT IS = "$1

他们的权限是

-rwxr-xr-x  1 user mygroup  209 May 14 15:32 script1
-rw-r--r--  1 user mygroup   38 May 14 15:29 script2

结果是

user@machine:~/test$ ./script1
@script1: # OF ARGUMENTS = 0
@script1: inside a fuction
@script2: # OF ARGUMENTS = 0
@script2: ARGUMENT IS = 
@script1: outside a fuction
@script2: # OF ARGUMENTS = 0
@script2: ARGUMENT IS = 

user@machine:~/test$ ./script1 1
@script1: # OF ARGUMENTS = 1
@script1: inside a fuction
@script2: # OF ARGUMENTS = 0
@script2: ARGUMENT IS = 
@script1: outside a fuction
@script2: # OF ARGUMENTS = 1
@script2: ARGUMENT IS = 1

user@machine:~/test$ . script1
@script1: # OF ARGUMENTS = 0
@script1: inside a fuction
@script2: # OF ARGUMENTS = 1
@script2: ARGUMENT IS = 2
@script1: outside a fuction
@script2: # OF ARGUMENTS = 1
@script2: ARGUMENT IS = 2

user@machine:~/test$ . script1 1
@script1: # OF ARGUMENTS = 1
@script1: inside a fuction
@script2: # OF ARGUMENTS = 1
@script2: ARGUMENT IS = 2
@script1: outside a fuction
@script2: # OF ARGUMENTS = 1
@script2: ARGUMENT IS = 2

1 个答案:

答案 0 :(得分:0)

The POSIX standard for .确实不要求它接受参数,而是使用调用它的脚本/函数的位置参数。允许使用显式参数作为扩展名:

  

KornShell版本的dot采用设置为位置参数的可选参数。这是一个有效的扩展,允许点脚本的行为与函数相同。