2013-04-17 156 views
1

試圖讓這個腳本來顯示數據,導出到文件,然後退出到終端。腳本運行正常,但不會退出。我必須每次都按Ctrl + c。我嘗試了kill,return和exit這兩個命令,但都沒有成功。欣賞任何建議。這讓我瘋狂。退出bash腳本到終端

#!/bin/bash 
#Script that displays data about current directory. 
echo 

echo -n "Number of subdirectories in this directory: " 
find . -type d | wc -l 
sleep 2 
echo 

echo -n "List of files in the current directory: " 
ls -1 | wc -l 
sleep 2 
echo 

echo "List of zero-length files in current directory: " 
find -size 0 
sleep 2 
echo 

echo "Used storage space of the current directory is: " 
du -sh 
sleep 2 
echo 

echo -n "Data output of 'dirchk.sh' is in this directory called directory-check.results." 

./dirchk.sh > directory-check.result 

回答

0

如果當前腳本是dirchk.sh,那麼它將在無限循環中運行。 dirchk.sh運行dirchk.sh,運行dirchk.sh ......爲了避免這種情況,可以使用tee命令:

#!/bin/bash 
#Script that displays data about current directory. 
echo 

echo -n "Number of subdirectories in this directory: " 
(find . -type d | wc -l 2>&1) | tee directory-check.result 
sleep 2 
echo 

echo -n "List of files in the current directory: " 
(ls -1 | wc -l 2>&1) | tee -a directory-check.result 
sleep 2 
echo 

echo "List of zero-length files in current directory: " 
(find . -size 0 2>&1) | tee -a directory-check.result 
sleep 2 
echo 

echo "Used storage space of the current directory is: " 
(du -sh 2>&1) | tee -a directory-check.result 
sleep 2 
echo 

echo -n "Data output of 'dirchk.sh' is in this directory called directory-check.results." 
0

您可以使用 Command grouping 避免重複tee電話

{ 
    set $(find . -type d | wc -l) 
    echo "Number of subdirectories in this directory: $*" 

    set $(ls -1 | wc -l) 
    echo "List of files in the current directory: $*" 

    set $(find -size 0) 
    echo "List of zero-length files in current directory: $*" 

    set $(du -sh) 
    echo "Used storage space of the current directory is: $*" 

    echo "Data output of 'dirchk.sh' is in this directory called" 
    echo "directory-check.results." 
} | tee directory-check.results 
-1

編輯:好吧,我有重點。錯誤發生在腳本結尾,不會讓您退出。 我可以建議你使用這樣的功能嗎?

#!/bin/bash 
#Script that displays data about current directory. 
echo 
testing() { 
echo "Number of subdirectories in this directory: $(find . -type d | wc -l)" 
sleep 2 
echo 

echo "List of files in the current directory: $(ls -1 | wc -l)" 
sleep 2 
echo 

echo "List of zero-length files in current directory: $(find -size 0)" 
sleep 2 
echo 

echo "Used storage space of the current directory is: $(du -sh)" 
sleep 2 
echo 
} 

testing 2>&1 |tee directory-check.results && echo "Data output of dirchk.sh is in this directory called directory-check.results." 
exit