Bash函数组件独立工作但不能一起工作

时间:2012-03-20 22:53:34

标签: bash function grep vi

我有一个包含此功能的bash脚本:

function start_vi()
{
   echo "Please enter a file name with complete path to open in vi:"
   read input_file

   if [ -d "$input_file" ]
   then
      echo "You entered a directory."
      echo "Please try again and enter a readable/writable file."
   fi

   grep_var="file $input_file | grep -c data"

   if [ $? -eq 0 ]
   then
      vi $input_file
   else
      echo "File not found or invalid file type. Please try again."
   fi
}

在大多数情况下,该功能正常。我的问题是两个if语句独立工作,例如,如果我注释掉其中一个,测试工作,它做我想要的。但是,如同编写的那样,例如,当我在提示符下键入目录时,vi将其作为文件打开,其中测试应该返回一个echo,表示它是一个目录,就像单独运行时一样。

关于这是为什么的任何想法?我在bash脚本方面仍然相对较新,所以专业人士可能很容易,但是我已经在墙上敲了一会儿。

提前致谢。

4 个答案:

答案 0 :(得分:3)

在第一个return中添加if/then语句:

function start_vi()
{
   echo "Please enter a file name with complete path to open in vi:"
   read input_file

   if [ -d "$input_file" ]
   then
      echo "You entered a directory."
      echo "Please try again and enter a readable/writable file."
      return
   fi

   grep_var="file $input_file | grep -c data"

   if [ $? -eq 0 ]
   then
      vi $input_file
   else
      echo "File not found or invalid file type. Please try again."
   fi
}

否则,它会打印然后打开文件,因为你的第二个测试应该是这样的:

   file $input_file | grep -c data

   if [ $? -eq 0 ]

$?是上次运行命令的退出代码。分配给变量(即grep_var="...")将$?设置为0.您似乎想要的是grep -c data的退出代码 - 在这种情况下,使用反引号`而不是引号“来运行命令,如下所示。或者您可以这样写:

   grep_var=`file $input_file | grep -c data`

   if [ $grep_var != 0 ]

比较字符串值(即grep -c data返回的内容 - data行的数量。)

执行上述操作可以解决问题。

答案 1 :(得分:1)

你需要的只是一个循环:

....

read input_file
while [ ! -f "$input_file" ]
do
      echo "You did not enter a file"
      echo "Please try again and enter a readable/writable file."
      read input_file
done

grep_var="file $input_file | grep -c data"

if [ $? -eq 0 ]
then
  vi $input_file
else
  echo "File not found or invalid file type. Please try again."
fi

答案 2 :(得分:1)

你需要一个循环

function start_vi()
{
   echo "Please enter a file name with complete path to open in vi:"
   read input_file

   while [ -d "$input_file" ]
   do
      echo "You entered a directory."
      echo "Please try again and enter a readable/writable file."
      read input_file
   done

   grep_var="file $input_file | grep -c data"

   if [ $? -eq 0 ]
   then
      vi $input_file
   else
      echo "File not found or invalid file type. Please try again."
   fi
}

答案 3 :(得分:0)

我认为这可能更接近你想做的事情。

function start_vi()
{
   echo "Please enter a file name with complete path to open in vi:"
   read input_file
   grep_var=`file $input_file 2>&1 | grep -c data`
   while [ $? -ne 0 ]
   do
      echo "File not found or invalid file type. Please try again."
      read input_file
      grep_var=`file $input_file 2>&1 | grep -c data`
   done
   vi $input_file
}