I want sth like: if [[ "$1" = "*" || "$1" = "all"]; then cat /etc/passwd elif [ -z $1 ]; then ls /var/log fi the problem is the wildcard, I can't figure out if user add a * to my script as an argument. Any idea??? Thank you
CodePudding user response:
wild() {
if [[ "$1" == '*' ]]
then echo "wildcard"
else echo "no wildcard"
fi
}
$ wild abc
no wildcard
$ wild *
no wildcard
$ wild '*'
wildcard
$ wild \*
wildcard
CodePudding user response:
When someone calls your script from a command prompt / shell, that shell already does the wildcard expansion, and your script doesn't even see the wildcard. Your script cannot tell the difference between
wild.sh 1 2 3 4 5 6 7 8 9
and
wild.sh ?
in a directory with files named from 1 to 9; your script receives the already expanded file names.
There are ways the wildcards are preserved:
If the pattern does not match, it's passed as is, e.g.,
*.txt
if there are no files ending in.txt
If the caller puts the wildcards into quotes or escapes them with a backslash, they won't get expanded:
wild.sh "*.txt"
orwild.sh '*.txt'
orwild.sh \*.txt
If you call your script from another program and don't involve a shell (e.g., Java's
ProcessBuilder
), you'd get the arguments as is, with any wildcard characters.
If you want to check whether someone passed wildcard characters that didn't get expanded, you also need to quote them in your code, btw:
if [ "$1" == * ]
then
echo ...
fi
If you run this in a directory with files named 1 to 9 again, it would expand to
if [ "$1" == 1 ]
then
echo ...
fi
(and $2
being 2, $3
being 3, and so on), which is probably not what you want, so quote or escape wildcards again:
if [ "$1" == "*" ] # or == '*'
then
echo ...
fi