This answer assumes that $1
is allowed to include subdirectories. If you are interested in the simpler case where $1
should be a simple directory name, then see one of the other answers.
Wildcards are not expanded when in double-quotes. Since $1
is in double-quotes, wildcards are not a problem.
Both ../
and symlinks can obscure the real location of a file. Shown below are tests to determine if the file is really, not just seemingly, under the path we want.
Newer systems: using realpath
As for finding out if the file is really if the file is really under /home/charlesingalls/
or not, you can use realpath
:
realpath --relative-base=/home/charlesingalls/ "/home/charlesingalls/$1" | grep -q '^/' && exit 1
The above runs exit 1
if the file specified by $1
is anywhere other than under the directory /home/charlesingalls/
. realpath
canonicalizes the whole path, eliminating both symlinks and ../
.
realpath
is part of GNU coreutils and should be available on any Linux system.
realpath
requires GNU coreutils 8.15 (Jan 2012) or better.
Examples
To demonstrate how realpath follows ../
to determine the real location of a file (for examples, the -q
option to grep is omitted so that the actual output of grep is visible):
$ touch /tmp/test
$ realpath --relative-base=$HOME "$HOME/../../tmp/test" | grep '^/' && echo FAIL
/tmp/test
FAIL
To demonstrate how it follows symlinks:
$ ln -s /tmp/test ~/test
$ realpath --relative-base=$HOME "$HOME/test" | grep '^/' && echo FAIL
/tmp/test
FAIL
Older systems: using readlink -e
readlink
is also capable of cononicalizing a path, following both symlinks and ../
:
readlink -e "$HOME/test" | grep -q "^$HOME" || exit 1
Using the same example files:
$ readlink -e "$HOME/../../tmp/test" | grep "$HOME" || echo FAIL
FAIL
$ readlink -e "$HOME/test" | grep "^$HOME" || echo FAIL
FAIL
In addition to being available on older GNU systems, versions of readlink
are available on BSD.
/
. Wildcards aren't interpreted inside quotes.-r
withrm
.rm -r
is for recursive deletion of a directory and all files and directories beneath it. It is only useful when deleting directories. More generally, don't cargo-cult. i.e. don't just copy things that look useful into your command line or script without understanding what they do or how they work. The plane gods that bring the magic cargo can get angry and delete all your files.