-1

I thought the single quotes simply reserve the literal value of each character within the quotes and do not interfere with the command result except for those character-escaping situations.

For example, the two commands below returned the same result.

$ ls /home/testuser/tmp1
$ ls '/home/testuser/tmp1'

This command below ran successfully.

$ cp /home/testuser/tmp1/* /home/testuser/tmp2

However, the command below ran into error.

$ cp '/home/testuser/tmp1/*' /home/testuser/tmp2 
cp: cannot stat '/home/testuser/tmp1/*': No such file or directory

What did I do wrong here?

Seaport
  • 153
  • 2
  • 14
  • 1
    You're explicitly preventing the glob expansion, and as it tells you there isn't a file literally named `*` in that directory. – jonrsharpe Mar 27 '20 at 17:13

1 Answers1

0

* is what you call a character escaping situation. Since you preserved the literal value of *, it lost its meaning of "all files", and cp instead tries to copy a file named literally *.

When you run:

cp /home/testuser/tmp1/* /home/testuser/tmp2 

The shell will transparently rewrite it into:

cp /home/testuser/tmp1/bar /home/testuser/tmp1/foo /home/testuser/tmp2 

This process is known as "pathname expansion" or "globbing". When you quote the *, this rewrite does not happen.

that other guy
  • 116,971
  • 11
  • 170
  • 194
  • Thanks for the help. The reason I use single quotes is to handle a mounted windows file system, which has spaces in folder/file name. Now I have two more questions. 1. I understand that Linux accepts space in file/folder names. But the best practice is not to use spaces in any name, am I right? 2. If a directory name does contain spaces, how do I handle this file mask situation, aka copying all files? – Seaport Mar 27 '20 at 17:26
  • 1
    For my second question, I think I have to escape the space, right? For example, cp /home/testuser/tmp\ 1/* /home/testuser/tmp2 – Seaport Mar 27 '20 at 17:36
  • 1. It's best practices to avoid spaces and exotic characters in system files that are distributed broadly, but it's fine to have spaces in filenames for a user's data files and any tool that doesn't handle a filename like `Family Photos` is considered buggy. Sometimes users avoid this so they can write sloppier scripts for themselves, but that's their choice. 2. You can escape individual spaces or just quote everything *except* the `*`, like `'/home/testuser/tmp1/'*` – that other guy Mar 27 '20 at 17:39