0

Whenever I execute this script it says: no such file or directory. I'm not sure what I'm doing wrong here. I put quotes around it just in case if there is a space in the directory's name.

#!/bin/bash
read -p "Enter destination: " folder
folder=$(sed -e 's/^/"/' -e 's/$/"/' <<< $folder)
cd $folder
Harry
  • 15
  • 4
  • Put double-quotes *around* the variable, not *in* the variable. See [Why does shell ignore quoting characters in arguments passed to it through variables?](https://stackoverflow.com/questions/12136948/why-does-shell-ignore-quotes-in-arguments-passed-to-it-through-variables) – Gordon Davisson Nov 21 '20 at 08:40
  • This may help with your next problem: [Why I can't change directories using “cd”?](https://stackoverflow.com/q/255414/3776858) – Cyrus Nov 21 '20 at 08:43

1 Answers1

1

It is better to use quotes in the cd command, regardless of whether the directory has spaces or not, like this:

#!/bin/bash
read -p "Enter destination: " folder
cd "$folder"
pwd

Test:

enter image description here

Another solution (use with caution as it may cause other problems) is using eval in your code:

#!/bin/bash
read -p "Enter destination: " folder
folder=$(sed -e 's/^/"/' -e 's/$/"/' <<< $folder)
eval cd $folder

References:

Nelbren
  • 71
  • 7
  • 1
    Please don't use `eval` like this, it just adds ways for things to go weirdly wrong. – Gordon Davisson Nov 21 '20 at 08:42
  • Thanks, i read this reference ( https://unix.stackexchange.com/questions/278427/why-and-when-should-eval-use-be-avoided-in-shell-scripts ) and I recognize that eval without the corresponding sanitization is evil. – Nelbren Nov 21 '20 at 09:05