2015-11-03 55 views
0

我在SLES 11 SP3上使用GNU bash 3.2.51。在执行source filename时我注意到了一个不寻常的行为 - 它执行任何处理命令行参数$*的任何事情。

文件f1.sh

#!/bin/bash 
#this is only a test driver 
echo FYI PWD=$PWD 
./f2.sh "$*" 

文件f2.sh

#!/bin/sh 
#this is the application script 
echo args in f2.sh were $* 

文件f3.sh

#!/bin/bash 
#this is the real driver code 
echo FYI PWD=$PWD 
source ~/.bashrc 
./f2.sh "$*" 

当我执行f1.sh cat f2.sh我得到这似乎OK

以下
/tmp> ./f1.sh cat f1.sh 
FYI PWD=/tmp 
args were cat f1.sh 

但是,当我执行f3.sh cat f2.sh我得到的,很意外

/tmp> ./f3.sh cat f1.sh 
cat: f1.sh: No such file or directory 
cat: f1.sh: No such file or directory 
FYI PWD=/usr/app/DB/DB00 
./f3.sh: line 4: ./f2.sh: No such file or directory 

最后我决定修改f3.shshift掉任何剩余$*值执行source ~/.bashrc

#!/bin/bash 
#this is the real driver code 
echo FYI PWD=$PWD 
cmd="$*" 
while shift; do true; done #<<<<<<<<<<<<<<< get rid of hanging args 
source ~/.bashrc 
./f2.sh ${cmd} 

,但我之前不知道为什么这样工作。也许更有知识的人可以解释到底发生了什么。 (也许有一个选项)非常感谢。

+1

可能更适合使用'$ @'代替。 – fedorqui

+3

你的例子没有显示'source'使用'$ *',但是'source〜/ .bashrc'确实有很大的不同。检查你的'〜/ .bashrc'是否可以使用'$ *'。 – bfontaine

+0

你确定采购是在做吗?采购其他文件是否具有相同的行为?什么改变'f3.sh'中的'PWD'?你的'.bashrc'包含什么?它是否根据位置参数进行操作? –

回答

1

source不使用$*;但是找到另一个脚本在相同的上下文中执行它,并因此使其可用于$*。这里~/.bashrc可能使用$*[email protected]的脚本参数。

下面是origin.sh一个例子:

#! /bin/bash 
echo "  args before: $*" 
source ./script.sh 
echo "  args after: $*" 

script.sh

#! /bin/bash 
echo "args in the script: $*" 
# shift the list twice 
shift 
shift 

执行./origin.sh所示:

​​3210

这证实script.sh访问$*,可以使用它并修改它。

现在,如果我改变origin.sh执行script.sh,而不是采购它,它会在另一个shell得到评估,不会有机会获得origin.sh$*

#! /bin/bash 
echo "  args before: $*" 
./script.sh 
echo "  args after: $*" 

结果:

./origin.sh foo bar qux 
     args before: foo bar qux 
args in the script: 
     args after: foo bar qux 
+0

这是一个很好的解决方法 – Dinesh