cp cannot stat to ~/ in script

时间:2015-05-24 21:42:51

标签: bash

I am having a problem I just can't seem to get over in my bash script. Whenever I try to copy using cp to home folder in a script I get

cp: cannot stat '~/file.txt': no such file or directory 

My code is as follows:

#!/bin/bash
echo "file location"
read a
user inputs ~/file.txt
b=$(basename $a)
cp "$a" . /$b

Please help, it's probably a simple solution but I just can't figure it out.

3 个答案:

答案 0 :(得分:4)

Filename expansion isn't applied to variables, which can be checked with the following minimal example:

d="~"; ls $d
ls: cannot access ~: No such file or directory

Use the full path: /home/youruser/file.txt.

Alternatively, you can force the globbing with eval (but prefer not to.. it's eval..):

d=$(eval echo "$d")
echo $d                  # /home/user

答案 1 :(得分:1)

You could do something like

expanded_path=$(echo "$d" | "s:^~:$HOME:")

(that is, subtstitute the initial ~ for $HOME manually)

or force the user to use the full path. eval is evil (definitely for user-supplied input, it is). If you just want to copy in the current dir while keeping the original name, you can do:

cp "$src" .

No need to play with basename.

答案 2 :(得分:1)

您只需将~替换为$HOME

即可
read a
a=${a/\~/$HOME}

现在~/file将成为/home/user/file