I am doing some automation with shell scripting and I am having trouble running a python script in which its' path has spaces. Forgive me if I made any mistakes or bad practices in the code, I just started learning yesterday :).

Here is the code:

# grabs root directory from the script path
script_path="$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"

# removing spaces
proj_root_no_spaces="${proj_root/' '/'\ '}"

log_dir=${proj_root_no_spaces}/src/python/graph_log.py #path to python file relative to root project dir

# checking output
echo "$log_dir"
create_graphs="python3 \""$log_dir"\""
echo "$create_graphs"

# run command

This script gives this output:

1) /mnt/c/Users/Varun\ Govind/Desktop/roulette_BACKUP/roulette/src/python/graph_log.py 
2) python3 "/mnt/c/Users/Varun\ Govind/Desktop/roulette_BACKUP/roulette/src/python/graph_log.py"
3) python3: can't open file '"/mnt/c/Users/Varun\': [Errno 2] No such file or directory

The first line is the full path to the python file, you can see that there is a space in between my user name so I escaped it with a backslash. The second line is the full python command that I am running; in addition to escaping the space, I've surrounded the path with double-quotes. If I run that however, I get an error on line 3.

If I copy and paste line 2 directly into my shell, and run it, it works. I'm not sure why my command isn't working in my shell script. Is there something wrong with how I am escaping the spaces or running the python command?

1 Answer 1


Short answer: See BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail!

Long answer: Don't try to embed shell syntax (like quotes and escapes) in variables; variables are for data, not syntax. Instead, just put double-quotes around variable references (i.e. put the quotes around the variable, not in the variable). For the same reason, don't try to store commands in variables, just execute them directly.

Thus, skip proj_root_no_spaces and just store the path, unescaped spaces and all:

log_dir=${proj_root}/src/python/graph_log.py #path to python file relative to root project dir

Then don't store the python3 ... command in create_graphs, just execute it directly:

python3 "$log_dir"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .