0

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
1
  • 1
    Related: Bash FAQ 001. Commented Jul 14, 2021 at 16:38

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahh, thank you so much for your insightful comment, particularly on the quotes - this explanation makes sense. I was able to execute the program successfully on my end! I'll take a look at the BASH FAQ for further learning!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.