Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to pass literal character * as a command line argument in Bash?

Take the bash script wtf.sh

#!/bin/bash
echo $1
echo $2
echo $3
./wtf.sh 1 2 3 
1 
2
3

./wtf.sh * * * 



end

./wtf.sh 1 * * 
1
wtf.sh
wtf.sh 

./wtf.sh 1 "*" "*"
1
wtf.sh
wtf.sh

I'm aware that * is special parameter in Bash but does that mean it's impossible to pass the * by itself as a literal character from the command line? What I was expecting was

./wtf.sh * * * 
* 
* 
*

How do I accomplish this?

like image 554
Peter Avatar asked Mar 18 '23 04:03

Peter


1 Answers

You can pass a literal * by:

  • Putting it in quotes: "*"

  • Putting it in apostrophes: '*'

  • Backslash escaping it: \*

Those are all equivalent (in this case).

The reason that didn't work is that your script has a problem: when you don't quote $1 (and $2 and $3), you are telling the shell to perform pathname expansion and word splitting on their contents. That's actually almost never what you want -- and it clearly isn't what you want in this case. So your script should read:

#!/bin/bash
echo "$1"
echo "$2"
echo "$3"

Here, the arguments must be surround with double quotes ("$1"), which allows parameter expansion to take place, but inhibits pathname expansion and word splitting.

like image 81
rici Avatar answered Apr 06 '23 10:04

rici