Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot open file when pass $1, but can open file when pass the file name

This might be a naive question, but I am new to bash scripting. I am trying to open a file and count the number of lines in that file and if it is greater than 4, then output something. I have figured out how to pass and save the line count to a variable, but I cannot access the file in the bash when I do not pass it the exact name. Therefore, I have this program called new_test written as so:

test_function()
{
    file_name='test_text.txt'
    n=$(wc -l < $file_name)
    if [ 'n > 2' ]
    then
        echo "Too many lines"
    fi
}
test_function

This program works, but when I try and make it more generic to accept any file by changing line 3 from:

file_name='test_text.txt'

to

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

file_name=$1

And then call

./new_test test_text.txt

it outputs:

./test_file[4]: : cannot open

From my understanding, the $1 is the second argument passed, and in the case of ./new_test test_text.txt, this would be the test_text.txt file. Do I need to obtain the address of the second argument or is the notation different in order to do this? Thank you in advance.

>Solution :

The $1 inside of the function is the function argument, not the script argument. You need to take that top level argument and pass it back into the function itself.

test_function()
{
    file_name="$1"
    n=$(wc -l < $file_name)
    if [ 'n > 2' ]
    then
        echo "Too many lines"
    fi
}
test_function "$1"

Make sure you don’t forget the quotes either, or you’ll run into problems with files that have spaces in their path.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading