Reputation: 77
I'm currently learning the basics of bash scripting (coming from a Pythonic background) and It seems I've run into an interesting situation in which I need a bit of explanation with.
My goal is to create a Path variable that contains a text file. I use an if-statement to check whether the file exists in the directory. If it exists, It will print "It exists".
Then I created a for-loop to print out the elements in the file list. When I execute the program, there is no output and no errors being thrown.
Any help or explanation would be much appreciated! Here is the code below:
#!/bin/bash
veggieFile=/home/lynova/Potato/hewwo.txt
if [ -e veggieFile ]; then
echo "File exists"
for VEGGIE in $(cat veggieFile ); do
echo "Veggies are ${VEGGIE}"
done
fi
Upvotes: 0
Views: 32
Reputation: 530920
You are checking if the file veggieFile
exists, not the file whose name is stored in the variable veggieFile
. You need to expand the name:
if [ -e "$veggieFile" ]; then
echo "File exists"
while IFS= read -r veggie; do
echo "Veggies are $veggie"
done < "$veggieFile"
fi
See Bash FAQ 001 for more information on why I used a while
loop instead of a for
loop. Also, all-caps names are reserved; use lower- or mixed-case names for your own variables.
A possible source of confusion might be in how quotes are used. In Python, veggieFile
would be a variable whose value is used, while "veggieFile"
is a literal string. In shell, though, all strings are literal strings; quotes are only used to escape the contained characters. For example, the quoted word "foo bar"
is equivalent to the foo\ bar
. You need to use $
to get the value of a variable.
Upvotes: 1