sudo not working with wildcard matching?

When working with sudo, one subtle thing is about shell wildcard matching. I didn’t notice this until recently I needed to use a script to copy files from a remote server with one user A, but eventually put the files under another user B with changing owernship and permissions. My steps were scp, mv, chown, then chmod. The files were under a directory with prefix hf-xxxx, xxx is the version number.

The first 3 steps were working fine, but the last step chmod failed with the error:

service@joetest:~$ sudo chmod 750 /opt/oracle/hf_*/*.sh

chmod: cannot access '/opt/oracle/hf_*/*.sh': No such file or directory

If I change to the root user, “chmod 750 /opt/oracle/hf_*/*.sh” actually works, it means shell wildcard expansion works.

So I started to look into it and realized that with sudo, wild expansion happens at your current shell first, and the expanded paths are passed to the sudo command. That means the user A needs to be able to access the directory “hf_xxxx” in my case. If the user doesn’t have the permission, wildcard expansion will fail and the command string is passed to sudo as is — the character “*” is treated literally, no wildcard expansion with sudo. Then sudo will fail as well.

For my task, it’s easy to workaround this, I just switched the order of chmod & chown because when I copied files over, the user A was the owner, so “sudo chmod” would work, then change the ownership as the last step.

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 )

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