将参数传递给exec调用的脚本会产生不需要的结果

时间:2016-08-13 13:17:04

标签: bash shell unix quotes

我正在尝试通过另一个shell脚本中的 exec 将参数传递给shell脚本。但是,我得到一个错误,脚本在路径中不存在 - 但事实并非如此。

$ ./run_script.sh 
$ blob has just been executed.
$ ./run_script.sh: line 8: /home/s37syed/blob.sh test: No such file or directory

由于某种原因,它将整个执行视为脚本的一个完整绝对路径 - 它不是将字符串作为 blob.sh 的参数读取。

这是正在执行的脚本。

#!/bin/bash
#run_script.sh
blobPID="$(pgrep "blob.sh")"
if [[ -z "$blobPID" ]]
then
    echo "blob has just been executed."
    #execs as absolute path - carg not read at all
    ( exec "/home/s37syed/blob.sh test" )
    #this works fine, as exepcted
    #( exec "/home/s37syed/blob.sh" )
else
    echo "blob is currently running with pid $blobPID"
    ps $blobPID
fi

该脚本由 run_script.sh 调用,没有做太多,只是模拟了一个很长的进程/任务:

#!/bin/bash
#blob.sh
i=0
carg="$1"
if [[ -z "$carg" ]]
then
    echo "nothing entered"
else
    echo "command line arg entered: $carg"
fi
while [ $i -lt 100000 ];
    do
    echo "blob is currently running" >> test.txt
    let i=i+1
done

以下是我正在使用的Bash版本:

$ bash --version
GNU bash, version 4.2.37(1)-release (x86_64-pc-linux-gnu)    

对于为什么会发生这种情况的任何建议/意见/帮助将不胜感激!

提前致谢,

s37syed

1 个答案:

答案 0 :(得分:3)

Replace

exec "/home/s37syed/blob.sh test"

(which tries to execute a command named "/home/s37syed/blob.sh test" with no arguments)

by

exec /home/s37syed/blob.sh test

(which executes "/home/s37/syed/blob.sh" with a single argument "test").