我有一个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会将其作为一个文件打开,其中测试应该返回一个回显,说明它是一个目录,就像它单独运行时一样。
你知道为什么会这样吗?我在bash脚本编写方面还是个新手,所以这对专业人士来说可能很容易,但我已经有一段时间在碰壁了。
提前谢谢。
发布于 2012-03-21 07:00:03
在第一个if/then中添加一条return语句
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行的计数)。
执行上面的一些操作应该可以解决问题。
发布于 2012-03-21 06:59:29
你所需要的只是一个循环:
……
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发布于 2012-03-21 07:03:43
你需要一个循环
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
}https://stackoverflow.com/questions/9796250
复制相似问题