I have a bash script that has this function in it:
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
}
For the most part the function works fine. My problem is that the two if statements work fine independently, eg, if I comment out one of them, the test works and it does what I want. But together, as written, for example, when I type in a directory at the prompt, vi opens it as a file, where the test should return an echo saying that it’s a directory, as it does when functioning alone.
Any ideas on why this is? I’m still relatively new at bash scripting so it is probably easy for the pros, but I have been banging my head against the wall for a while now.
Thanks in advance.
Add a
returnstatement in the firstif/then:Otherwise, it will print and then open the file anyway, as your second test should be like this:
The
$?is the exit code of the last run command. Assigning to a variable (i.e.grep_var="...") sets$?to 0. What you seem to have wanted is the exit code ofgrep -c data– in that case, use backticks ` instead of quotes ” to run commands, like below. Or you can write it like this:to compare the string value (i.e. what
grep -c datareturns – the count ofdatalines).Doing some of the above should solve the problem.