Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash variables with spaces

I'm facing the next problem in MinGW shell under windows. I have in my /etc/profile the expression:

export GIT_SSH="/c/Program Files/TortoiseGit/bin/TortoisePlink.exe" 

This doesn't work when I use git fetch on the local repository. But if I do it like this (old DOS way), it works:

export GIT_SSH="/c/Progra~1/TortoiseGit/bin/TortoisePlink.exe" 

My question is:

How can I make it work using spaces in the variable?

For testing purpose you can simulate something like this (any example is good):

export VAR="/c/Program Files/TortoiseGit/bin/TortoisePlink.exe" # and try to execute like this $VAR 

Is there a solution for this (other than the previous mentioned)?

like image 953
INS Avatar asked Apr 28 '11 13:04

INS


People also ask

How do you handle spaces in Bash?

Filename with Spaces in Bash A simple method will be to rename the file that you are trying to access and remove spaces. Some other methods are using single or double quotations on the file name with spaces or using escape (\) symbol right before the space.

Does spaces matter in Bash?

You must separate all arguments of a command with spaces. You must separate a command and the argument, that follows after, with a space.

How do you represent a space in Bash?

To cd to a directory with spaces in the name, in Bash, you need to add a backslash ( \ ) before the space. In other words, you need to escape the space.

How do you pass arguments with spaces to a shell script?

Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth. The variable $0 references to the current script.


1 Answers

Execute it like this: "$VAR". This is one of the most significant gotchas in shell scripting because strings are always substituted literally and any contained spaces are treated as token delimiters rather than as characters of the string. Think of substituting a variable as a kind of code pasting at runtime.

What really happens when you write $VAR is that the shell tries to execute the binary /c/Program with a first argument Files/TortoiseGit/bin/TortoisePlink.exe.

I learned this the hard way by getting a strange syntax error in a big shell script for a particular input. No other languages I can think of can complain for syntax errors if the runtime input contains special characters - but that is the nature of shell scripting since command interpreters like bash and sh interpret the code line by line.

Whenever you expect a string to contain spaces and you don't want to treat it as separate tokens, enclose it in double quotes.

like image 178
Blagovest Buyukliev Avatar answered Sep 22 '22 13:09

Blagovest Buyukliev