Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get unexpanded argument from bash command line

When passing a glob expression as an argument to a script from the bash command line, it gets expanded, and the files matching it are unpacked into sys.argv:

# stuff.py
import sys

print(sys.argv)
host:~$ python stuff.py a*
['stuff.py', 'a1', 'a2', 'a3']

I would like to get these files in an container, as a single element of sys.argv:

host:~$ python stuff.py a*
['stuff.py', ['a1', 'a2', 'a3']]

I know that putting the glob expression in quotes and using the glob module solves the problem:

import sys
import glob

print(glob.glob(sys.argv[1]))
host:~$ python stuff.py "a*"
['a1', 'a2', 'a3']

However, this requires to add quotes around the arguments, so tab-completion cannot be used directly.

Is it possible to prevent the command line arguments from being expanded?

like image 252
Right leg Avatar asked Nov 18 '25 01:11

Right leg


1 Answers

Get unexpanded argument from bash command line

The only way to pass an argument unexpanded by the shell is to either quote it or to use appropriate escapes. Specifically, to quote or escape the portions that the shell would try to expand.

However, this requires to add quotes around the arguments, so tab-completion cannot be used directly.

You don't need to add quotes around entire arguments. It's enough to do that around characters that have special meaning in the shell.

For example, if you autocomplete this command line until this point:

python stuff.py file_00
                       ^ cursor is here, and you have many files,
                         for example file_001, file_002, ...

At this point, if you want to add a literal * to pass file_00* to the Python script without the shell interpreting it, you can write like this:

python stuff.py file_00\*

Or like this:

python stuff.py file_00'*'

As a further example, note that when the file pattern contains spaces, tab completion will add the \ correctly, for example:

python stuff.py file\ with\ spaces\ 00

Here too, you can add the escaped * as usual:

python stuff.py file\ with\ spaces\ 00\*

In conclusion, you can use tab completion naturally, and escape only the special characters after the tab completion. And then use the glob Python module to expand the glob parts in arguments.

like image 156
janos Avatar answered Nov 20 '25 16:11

janos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!