Why can't "sudo cp" find the files?
The shell attempts expansion of the glob pattern before it passes the expanded result to cp
(actually, it is passing the result to sudo
which then passes it unchanged to cp
). Since the shell (it is running as you, not root) is not able to traverse the directory, cp
ends up receiving the unexpanded pattern in its argument list.
cp
does not perform any glob expansion itself. It expects a list of file names. The string with the pattern in it does not name a file.
Perhaps the most straight forward way to perform the task is to invoke your command in a sub-shell. Quote the command with either double quotes ("
) or single quotes ('
).
sudo sh -c "cp /data/*20150522* /backup/"
sudo sh -c 'cp /data/*20150522* /backup/'
This works because the sub-shell expands the glob pattern in the command string before invoking the command. Since the sub-shell is running as root under sudo
, the expansion is successful.
Using double quotes to quote the command to the sub-shell allows the parent shell to expand shell variables before invoking the sudo
command. If you want variables to be expanded by the sub-shell, the single quotes should be used instead. In this case, it is equivalent, since you do not have any variables. But, you could add one to see the difference in behavior.
sudo sh -c "echo $USER; cp /data/*20150522* /backup/"
sudo sh -c 'echo $USER; cp /data/*20150522* /backup/'
The first command will display your user name, while the second command will display the root user name.