2010-06-20 247 views
2

以下测试脚本存在问题。当我在脚本中添加(sleep 5)&行时,while read循环不读取文件中的所有行,但只打印第一行。while while循环+在while循环中创建aproccess

但是,当我从脚本中删除(sleep 5)&时,脚本将打印文件中定义的所有行。

为什么(sleep 5)&会导致这种情况?

如何解决这个问题?我想在while循环中创建一个新的进程(睡眠只是一个例子)。

$ more test 

#!/bin/ksh 
while read -r line ; do 
echo $line 
(sleep 5)& 
RESULT=$! 
sleep 1 
kill $RESULT 
done < file 


$ more file 
123 aaa 
234 bbb 
556 ccc 
+0

KSH哪个版本您使用的?就像吉尔斯提到的,我没有在ksh93t +上看到它 – tomkaith13 2011-06-24 20:41:41

回答

0

您提供的代码运行并打印文件中的每一行。

既然你不等待

(sleep 5) & 

子进程,但对过程的执行没有影响。这是你写的EXACT代码吗?

0

这似乎是一个特定版本的ksh中的错误。我从ksh 93s +中获得了同样的效果,但不是来自bash,ash,pdksh,zsh或ksh 93t +。

0

这KornShell(KSH)脚本工作正常,我这个版本:

  • echo $KSH_VERSION
    • @(#)MIRBSD KSH R48 2013/08/16

soExample.ksh:

#!/bin/ksh 

#Initialize Variables 
file=file 
fileContent="123\taaa\n234\tbbb\n556\tccc" 

#Function to create File with Input 
#Params: 1}Directory 2}File 
createBlankFileHere(){ 
    echo "Entering createFileHere" 
    > ${1} 
    echo "Exiting createFileHere" 
} 

#Function to create File with Input 
#Params: 1}File 2}String to write to FileName 
createFileWithInputHere(){ 
    echo "Entering createFileWithInputHere" 
    > ${1} 
    #-e means 'enable interpretation of backslash escapes 
    echo -e ${2} >> ${1} 
    #print ${2} >> ${1} 
    echo "Exiting createFileWithInputHere" 
} 

#Function to 
#Params: 1} File 
readLine(){ 
    echo "Entering readLine" 
    while read -r line ; do 
    echo ${line} 
    (sleep 5)& 
    RESULT=${!} 
    sleep 1 
    kill ${RESULT} 
    done < ${1} 
    echo "Exiting readLine" 
} 

#----------- 
#---Main---- 
#----------- 
echo "Starting: ${PWD}/${0} with Input Parameters: {1: ${1} {2: ${2} {3: ${3}" 
createFileWithInputHere ${file} ${fileContent} #function call# 
readLine ${file} #function call# 
echo "Exiting: ${PWD}/${0}" 

soExample.ksh输出:

[email protected] /tmp 
$ ksh soExample.ksh 
Starting: /tmp/soExample.ksh with Input Parameters: {1: {2: {3: 
Entering createFileWithInputHere 
Exiting createFileWithInputHere 
Entering readLine 
123 aaa 
234 bbb 
556 ccc 
Exiting readLine 
Exiting: /tmp/soExample.ksh