退出Bash脚本到终端

时间:2013-04-17 19:39:12

标签: bash

尝试让此脚本显示数据,导出到文件然后退出到终端。脚本运行正常,但不会退出。我每次都要按Ctrl + c。我已经尝试了命令kill,return和exit但没有成功。感谢任何建议。这让我发疯了。

#!/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

3 个答案:

答案 0 :(得分: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."

答案 1 :(得分: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

答案 2 :(得分:-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