LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Handling directories with white spaces in bash script (https://www.linuxquestions.org/questions/linux-newbie-8/handling-directories-with-white-spaces-in-bash-script-4175490141/)

jms89 01-04-2014 01:12 PM

Handling directories with white spaces in bash script
 
Hey all, I'm new to bash-scripting and trying to write a script which involves calling a command with a string stored as a variable, which is a directory path that contains whitespaces.

For example, consider the following very simple script;

Code:

#! /bin/bash
path="./this\ is\ a\ test\ dir/"

ls $path

The output of the script is,
Code:

./test.sh
ls: cannot access ./this\: No such file or directory
ls: cannot access is\: No such file or directory
ls: cannot access a\: No such file or directory
ls: cannot access test\: No such file or directory
ls: cannot access dir/: No such file or directory

however typing the command directly in the terminal works fine,
Code:

ls ./this\ is\ a\ test\ dir/
success!.txt

Can someone explain how to properly handle the whitespaces in the directory name (using the example script I posted) so I can accomplish what I'm trying to?

Thanks!

suicidaleggroll 01-04-2014 02:17 PM

You need to quote it when it's used

Code:

$ path=this\ is\ a\ test
$ ls "$path"
ls: cannot access this is a test: No such file or directory
$ path="this is a test"
$ ls "$path"
ls: cannot access this is a test: No such file or directory


jms89 01-04-2014 02:39 PM

Ah, I tried that but I guess you can't use the '\ ' delimiters and quotes at the same time... thanks!


All times are GMT -5. The time now is 04:57 AM.