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.

1
  • 1
    Python supports semicolons as statement separators, what if you try to replace the \n with ; ? Commented Oct 24, 2020 at 9:23

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.