Harry
Harry

Reputation: 15

Bash script to change directory from user input

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

Upvotes: 0

Views: 1362

Answers (1)

Nelbren
Nelbren

Reputation: 71

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:

Upvotes: 1

Related Questions