1

In bash, I ask a user to enter the absolute path of a file, such as dir/to/the/file.txt and then go to that directory and run some commands. But I just cant get to the supplied directory.

I've tried the scripts below, and if it doesn't throw me an error, it just outputs a single "."

#!/bin/bash read -p "Please Enter Path:" $r1 parent=$(dirname "${r1}") echo "${scriptdir}" #!/bin/bash read -p "Please Enter Path:" $r1 parent=$(readlink -f "$(dirname "$r1")") cd $parent #!/bin/bash read -p "Please Enter Path:" $r1 parent="$(basename "$(dirname "$r1")")" echo "$parent" 

What am I doing wrong?

3
  • 2
    read -p "Please Enter Path:" $r1 -> read -p "Please Enter Path:" r1. Generally quote variables everywhere, cd "$parent". It outputs a single ., because r1 variable is empty, you basically run dirname "", which outputs .. Commented Jan 13, 2020 at 14:04
  • I dont understand what you said much, I have tried with quotes and without still can not. thou I have tried above commands with many options. Commented Jan 13, 2020 at 14:36
  • 1
    It's not about quoting. It is because you provided a null string instead of a variable name where read would store the value being read. An alternative would be to not write anything for a variable, in which case the answer would be stored in the special variable REPLY. For instance read -p "Enter Path"; parent=$(dirname $REPLY). Commented Jan 13, 2020 at 15:26

1 Answer 1

4

As KamilCuk pointed out, when executing the read command, it should put the supplied value into the r1 variable. This is done without the $.

So:

read -p "Please Enter Path: " r1 

instead of:

read -p "Please Enter Path: " $r1 

Also, when printing a variable, the brackets are not required:

echo "$parent" 

instead of

echo "${parent}" 

If you apply these fixed, the first script should work:

#!/bin/bash read -p "Please Enter Path:" r1 parent=$(dirname "$r1") cd "$parent" 

EDIT: The user Adhoc added a good remark: if we add the -r parameter to the read command, backslashes will not behave as escape characters. This will change the script as follows:

#!/bin/bash read -p "Please Enter Path:" -r r1 parent=$(dirname "$r1") cd "$parent" 
Sign up to request clarification or add additional context in comments.

1 Comment

I would even suggest using read -p "Please Enter Path:" -r r1 Especially if the path ends up being a Windows path, you will have backslashes that will get mangled if you don't use -r. More at github.com/koalaman/shellcheck/wiki/SC2162

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.