Wild behavior of wildcards

While playing with files on one of Linux server I’ve observed strange behavior with wild card “*”.

[oraxxx@vision test]$ cat a1.txt
1
[oraxxx@vision test]$ cat a2.txt
2

[oraxxx@vision test]$ ls
a1.txt  a2.txt
[oraxxx@vision test]$ cp a*.txt
[oraxxx@vision test]$ echo $?
0

This command is expected to fail as we did not provide any destination folder
But it got succeeded as the shell has translated a*.txt to “a1.txt a2.txt”
Finally “cp a*.txt” translated to “cp a1.txt a2.txt”

[oraxxx@vision test]$ cat a1.txt
1
[oraxxx@vision test]$ cat a2.txt
1

Little more play revealed more interesting behavior.

[oraxxx@vision test]$ mkdir a3
[oraxxx@vision test]$ ls -ltr
total 24
-rw-r--r-- 1 oraxxx dba    2 Jun 22 04:31 a1.txt
-rw-r--r-- 1 oraxxx dba    2 Jun 22 04:31 a2.txt
drwxr-xr-x 2 oraxxx dba 4096 Jun 22 10:26 a3
[oraxxx@vision test]$ cp a*
[oraxxx@vision test]$ echo $?
0
[oraxxx@vision test]$ ls -l `pwd`/a3
total 16
-rw-r--r-- 1 oraxxx dba 2 Jun 22 10:26 a1.txt
-rw-r--r-- 1 oraxxx dba 2 Jun 22 10:26 a2.txt

This behavior is valid as long as the wildcard character results in only 2 files. It is also valid if the last one resulted is a directory.
We just need to be careful while using commands similar to these. You never know when you’ll overwrite an important file.

One thought on “Wild behavior of wildcards

  1. Interesting,logical though,even cp command can become very dangerous with *. While going through this post, I remembered how VGilda used to tell us to be careful on PROD envs.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s