1

I am totally new to bash scripting but wanted to give it a try. I wrote a simple and quick script for a backup of a directory.

#!/bin/bash

echo "Enter your source"
read source

echo "Enter your target"
read target

backup(){
    cp -r $source $target
}

backup source target

exit 0

However, once I run it it doesn't recognize the directory path. It gives out: cp: cannot stat '~/Desktop/week46': No such file or directory Even though the directory exists and when i manually run cp -r ~/Desktop/week46 ~/Desktop/week47 it is working.

What am I doing wrong?

  • 1
    Are you sure that you executed it as a bash script? You are posting just the content of the script, but not how you run it. – user1934428 Nov 17 '20 at 13:01
  • Well i guess so. First line of the file is: #!/bin/bash and i execute it like ./filename –  Nov 17 '20 at 13:07
  • 1
    This may be in relation: https://stackoverflow.com/questions/3963716/how-to-manually-expand-a-special-variable-ex-tilde-in-bash – James Brown Nov 17 '20 at 13:32
  • 1
    ... but I guess tilde doesn't expand when using `read`. Google _bash tilde expansion_ and you'll find resources. – James Brown Nov 17 '20 at 13:39
  • @JamesBrown : IMO, you should post this as answer, because this really looks like the explanation for the problem. – user1934428 Nov 17 '20 at 13:43
  • 1
    @HBJesus : From a programming design, asking the user for input from a script is rarely a good choice. Why don't you take `source` and `target` from the parameters? This also saves you from the tilde-expansion-problem. – user1934428 Nov 17 '20 at 13:44
  • Rather mark this as a duplicate if someone finds a better explanation. I tried looking but didn't find any - which would leave a place for a nice answer, though. – James Brown Nov 17 '20 at 13:47

1 Answers1

1

The program is unable to resolve the directory path because the read function reads the input as string in singlequotes (hence it won't interpolate/expand it's contents). So what it's executing is equivalent to cp -r '~/Desktop/week46' '~/Desktop/week47'.

When you execute in shell you are passing without quotes, so the shell can easily resolve the relative paths.

What you can give a try is exploring some workarounds with readlink dirname and basename.

One possible solution might be:

RES_PATH=$(readlink $(dirname $source))
FILE=$(basename $source)
SRC=${RES_PATH}/${FILE}
Ankush
  • 573
  • 7
  • 11