2017-04-11 60 views
2

我想讓腳本在後臺運行(使用&),並檢查從鍵盤讀取的某個文件的名稱是否存在多個目錄,作爲參數給出。Bash shell腳本,只用腳本的某個部分運行&

因此,腳本將運行在while true循環中,直到創建具有給定名稱的文件。

問題是,當我運行腳本時,我從read中鍵入的內容被當作普通終端cmd。

這裏的腳本:

#!/bin/bash 

echo Type the file name 
read fileName 


while true 
do 
    for file in [email protected] 
    do 
     if find $file -name $fileName | grep -q "$fileName" 
     then 
      echo The file with name $fileName has been created!!! 
      break 
     fi 
    done 
done 

如果我不&運行腳本,它工作正常。

+2

加載的文件名作爲參數該腳本不是通過* read *來「加載」它。 'scriptname.sh filename' - >在你的腳本中,文件名可以通過'$ 1'變量訪問($ 1是第一個參數$ 2秒...)。 http://how-to.wikia.com/wiki/How_to_read_command_line_arguments_in_a_bash_script –

+2

由於您在Linux中,因此請考慮使用[**'inotifywait' **](http://unix.stackexchange.com/a/323919/13377 )而不是用一個while循環錘擊你的磁盤(或緩存)。 – ghoti

+1

但要回答你的問題......文件名被作爲shell輸入的原因是通過背景腳本,你從終端分離它,以便它不能接收輸入。如果你真的需要提供將由後臺腳本處理的輸入,請使用Fred的建議。 – ghoti

回答

3

我想你想要做的是發送沒有用戶輸入到後臺執行腳本的唯一部分。如果在腳本中使用&而不是在命令行中,則可以這樣做。

#!/bin/bash 

echo Type the file name 
read fileName 

while true 
do 
    for file in "[email protected]" 
    do 
     if find "$file" -name "$fileName" | grep -q "$fileName" 
     then 
      echo "The file with name $fileName has been created!!!" 
      break 
     fi 
    done 
done & 

請注意我已經添加額外的報價,以防止含有特殊字符的文件名的文件的情況下的問題。

如果需要,您也可以爲背景while循環選擇一個選項,以便在調用腳本時選擇您喜歡的行爲。

+0

是的,這就是我一直在尋找的!泰! –

0

我將這些命令取代你的腳本:

sleep 2; read -p "x=" x; echo "x=$x" 

你可以輸入不帶

echo Hello | sleep 2; read -p "x=" x; echo "x=$x" 

如果你想腳本放在一起改變「腳本」,用

echo Hello | (sleep 2; read -p "x=" x; echo "x=$x") 

將該命令放在ackground中似乎很好用:

echo Hello | (sleep 2; read -p "x=" x; echo "x=$x")& 

當你想擁有echo Hello在後臺,使用

(echo Hello | (sleep 2; read -p "x=" x; echo "x=$x"))& 
0

您可以通過在命令行中提供的文件名簡化了這一點,如果它是可以接受的,請參閱以下內容:

#!/bin/bash 

fileName="$1" 
shift 

while true 
do 
    for file in "[email protected]" 
    do 
     if find "${file}" -name "${fileName}" | grep -q "${fileName}" 
     then 
      echo The file with name ${fileName} has been created!!! 
      break 
     fi 
    done 
done 

您可以只需啓動:

$ ./script.sh FILE DIR1 DIR2 & 
+2

這也將搜索'$ 1'(這是'$ @'的成員)中的'$ fileName'。可能不是你想要的。 – ghoti

+0

不清楚你的意思...這兩個腳本是相同的,我建議只採用文件名作爲參數(這是$ 1) –

+2

你應該*真的,* *真正*使用'「$ @」'適當引用和類似的引號'「$ file」'和'「$ fileName」'。 – tripleee