Search code examples
bashwhitespacefile-format

Spaces are not recognised in the same way in a txt file and in a command line


I am using Mac. I have compiled a bytecode run, it can work on a string input in a command line like:

./run "Here is a text input"

To test run, I write inputs.txt that contains sever lines of inputs, one line represents one input:

"input1"
"This is input 2"
"input 3"

And, here is a test.sh:

#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
    echo "Text read from file: $line";
    ./run $line
done < inputs.txt

The problem is that, a test fails for input lines that contain space, although testing the same line in the command works.

So I guess, space is not interpreted the same when it is in inputs.txt and in a command line.

Does anyone know what to do to make spaces in inputs.txt interpreted in the same way as in a command line? Maybe should I change the format of inputs.txt?


Solution

  • I think you just need to change

    ./run $line
    

    to

    ./run "$line"
    

    That way, the use of $line won't be split into arguments before run is called.