Store paths containing directory with space in name

Asked

Viewed 761 times

2

I have the following problem: I need you to store a path from an X directory in a variable in my script. The big problem is that one of the folders in this path contains space in the name and for some reason when calling the variable gives a conflict in the directory with space. Ex:

If I use it like this it works:

cd "/home/douglas/Minha Pasta" 

But if so, it doesn’t work:

home="/home/douglas/Minha Pasta"
cd $home

Does anyone know how I can fix this ?

2 answers

5

You will need to escape the spaces for the command to work, when you use the command cd $home is the same as: /home/douglas/Minha Pasta, he will read until the My and you won’t find the folder;

Do home="/home/douglas/Minha\ Pasta", with the \ before space.

  • I’ve done all that and it doesn’t work :(

  • Which message appears?

  • 1

    I decided, thank you :)

3


Another option is to reference the variable between double quotes:

home="/home/douglas/Minha Pasta"
cd "$home"

According to the documentation, 5.1. Quoting Variables:

(In free translation)

When referencing a variable, it is generally advisable to include its name in double quotes.

This prevents the reinterpretation of all special characters within the chain between quotation marks - except $, `(severe accent), and \ (escape). [...]

Use double quotes to avoid separation of words. An argument is presented as a single word, even if it contains white space separators.

  • Doesn’t work :(

  • 1

    @Douglas In theory it was supposed to work, see this demo, click "Run" and see the output of cd. Which error is displayed on your machine?

  • Thanks, I had not noticed that the variable was between "". Now it worked, show.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.