user4661030
user4661030

Reputation:

Bash script cd doesn't work

Part of my bash script is to access a series of folders:

 #lsit of folders
locations=("/Volumes/Israel\ Hernandez/Quantitative\ Data/Microglia\ data/3\ month/Mutant/314a"
    "/Volumes/Israel\ Hernandez/Quantitative\ Data/Microglia\ data/3\ month/Mutant/314b"
    "/Volumes/Israel\ Hernandez/Quantitative\ Data/Microglia\ data/3\ month/Mutant/314c")

for i in "${locations[@]}"
do (
    #change to directory

    cd "$i"
    #convert tiff to png

However when I received errors:

/Users/luna/Documents/Ethan/scripts/microglia.sh: line 16: cd: /Volumes/Israel\ Hernandez/Quantitative\ Data/Microglia\ data/3\ month/Mutant/314a/: No such file or directory

I've tried to just cd into that folder on terminal and it absolutely worked. How come it just wont work in a shell script?

Upvotes: 0

Views: 263

Answers (3)

LF-DevJourney
LF-DevJourney

Reputation: 28554

before you cd command, you should process the escape space in you $i. here is the code, hope it helps.

#lsit of folders
locations=("/Volumes/Israel\ Hernandez/Quantitative\ Data/Microglia\ data/3\ month/Mutant/314a"
    "/Volumes/Israel\ Hernandez/Quantitative\ Data/Microglia\ data/3\ month/Mutant/314b"
    "/Volumes/Israel\ Hernandez/Quantitative\ Data/Microglia\ data/3\ month/Mutant/314c")

for i in "${locations[@]}"
do (

    #reverse esxape chars such space in you code
    i="echo \$\'"$(echo $i|sed -e 's|\\|\\\\|g')"\'"
    i=$(eval "echo $(eval $i)")
    i=$(eval "echo $(eval $i)")

    #change to directory
    cd "$i"
    #convert tiff to png

Upvotes: 0

李德康
李德康

Reputation: 15

The error is clearly:"No Such file or directory!" You can executive the command "cd /Volumes/Israel\ Hernandez/Quantitative\ Data/Microglia\ data/3\ month/Mutant/314a/" on the terminal.
if the error is "No such file or directory!",you should carefully check the path. Don't doubt the script parser itself!Just doubt your code!

Upvotes: 0

cxw
cxw

Reputation: 17051

You don't need the backslash escapes before the spaces since the spaces are already inside a double-quoted string. Your quoting is correct — rejoice! Remove the backslashes inside your "" strings and you should be set.

Upvotes: 1

Related Questions