1

I want to get run a python inline command together with variables from my bash script. It works without the import line.

for filename in *.txt; do
    OUT=$(python3 -c "import pprint\nprint('$filename')")
    mv $file $OUT
done

But I get the error message SyntaxError: unexpected character after line continuation character.

ikreb
  • 2,133
  • 1
  • 16
  • 35
  • 1
    Python supports semicolons as statement separators, what if you try to replace the `\n` with `; `? –  Oct 24 '20 at 09:23

1 Answers1

7

The \n gets passed in verbatim, and doesn't make sense to Python. The most expedient fix is probably to use a semicolon instead, which Python supports pretty much solely to allow you to write simple one-liners inside a script in another language.

    OUT=$(python3 -c "import pprint; print('$filename')")

You could also pass in an actual newline;

    OUT=$(python3 -c "import pprint
print('$filename')")

Though why do you import pprint when you are not using it? I guess you wanted to pprint() the filename, not print() it?

This could still fail if the filename contains a literal single quote. From the Python side, you could fix this by reading the string as a command-line argument.

    OUT=$(python3 -c "import pprint, sys; pprint.pprint(sys.argv[1])" "$filename")

As an aside, you should not use upper case for your private shell variables, and quote the variable.

for filename in ./*.txt; do
    out=$(python3 -c "import pprint, sys; pprint.pprint(sys.argv[1])" "$filename")
    mv "$file" "$out"
done

The added ./ avoids the problem that a filename which starts with a dash would be parsed as a (probably invalid) option to mv. Actually a better refactoring would be to perform the rename - and perhaps the loop, too! - in Python instead. Passing filenames correctly with quoting etc intact between tools is more challenging in shell script than it should be.

python3 -c 'import pprint, sys, shutil; for file in sys.argv[1:]: shutil.move(file, pprint.pformat(file))' ./*.txt
tripleee
  • 175,061
  • 34
  • 275
  • 318