2

I am very new to bash scripts. I have a .txt file with string names separated by lines (have space between each string).

my.txt is:

my name 
my class
my room

When I run my python script using terminal. I need to pass arguments one by one.

python3 python_file.py -f 'my name'
python3 python_file.py -f 'my class'
python3 python_file.py -f 'my room'

It works fine. I want to use bash script for each string (my name, my class, and my room) individually and pass as an argument for a python script.

#!/bin/bash
while read LINE; do
    #echo ${LINE}
    python3 pythonfile.py -f $LINE 
done < my.txt

It doesn't work as each string has a space between them (my name), python assumes as string and display error message

error: unrecognized arguments: name

When I ma trying to put quotes in bash script, it is not working.

#!/bin/bash
while read LINE; do
    echo \'${LINE}\'
    #python3 pythonfile.py -f $LINE 
done < my.txt 

output:
'my name
'my class
'my room

with same error message.

When I tried to put quotes inside .txt file, it doesn't even work then.

new: my.txt

'my name'
'my class'
'my room'

same error message:

error: unrecognized arguments: name

I do not want to do it with one python script by reading names one by one from my.txt file. I have some internal coding in python script that is not suitable for this. Hence I want to use bash.

Please guide.

manv
  • 138
  • 1
  • 10

2 Answers2

1

My Mac appears to give the expected output when I run this shell script:

#!/bin/bash
while read LINE; do
    echo python3 pythonfile.py -f \'${LINE}\'
    #python3 pythonfile.py -f $LINE
done < my.txt

Noting that you don't see the final quote in your output, and neither do you strip anything from the input, I suspect that your data file was generated in a Windows environment and contains <CR><LF> terminations for each line.

So what your script is outputting (the shell strips the terminating line feed) for each line of input is

'some name<CR>'<LF>

The effect of the carriage return is to overprint the first quote with the second one, making it "disappear". There's often a dos2unix or similar utility that will help you convert such data files.

holdenweb
  • 33,305
  • 7
  • 57
  • 77
  • I am new to bash as I mentioned. Yes the txt file was prepared in Windows. While passing the string (my name) it treats `'my'` as passing string for argument and treat `'name'` as second argument and shows error `unrecognized argument`. `python3 pythonfile.py -f "$LINE"`solved the issue. – manv Mar 04 '19 at 09:50
  • Yes, understanding the different quoting options is an essential part of the learning process. – holdenweb Mar 04 '19 at 12:50
0

The answer is given by Inian. Can not accept that comment as answer so posting it here.

It should have been python3 pythonfile.py -f "$LINE"

manv
  • 138
  • 1
  • 10