Linux Mastering Development

Issue running a python script in shell script that has spaces to the python script

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/ #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/ 
2) python3 "/mnt/c/Users/Varun\ Govind/Desktop/roulette_BACKUP/roulette/src/python/"
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?

Leave a Reply

Your email address will not be published. Required fields are marked *