Barak michaeli
Barak michaeli

Reputation: 113

recognize * as command in unix

while passing some rgument with the "*" char, my shell recognize it as the "ls myfolder" command , and so print to the stdout the result of this command.

Any way to fix this problem?

  1 #!/bin/bash
  2
  3 if [ $# -lt 3 ]; then
  4 echo "Some arguments are missing"
  5 fi
  6
  7 #passing "*" as argument 
  8 echo $2
  9 # the result is file1.txt file2.txt...and more..

Upvotes: 0

Views: 41

Answers (3)

chepner
chepner

Reputation: 531185

Parameter expansions undergo pathname expansion if you don't quote them.

#!/bin/bash

if [ $# -lt 3 ]; then
  echo "Some arguments are missing"
fi

# passing "*" as argument 
echo "$2"

Upvotes: 0

sjsam
sjsam

Reputation: 21965

Call the script either as

./script \*

or as

./script '*'

to strip the special meaning associated with * ie to prevent globbing.

Upvotes: 0

Tim
Tim

Reputation: 2187

Bash expands the * before the script is called, i.e., the $2 var gets populated with everything that is in that directory.

It is the same as calling:

./script.sh with every file listed separated by spaces as arguments

If you reall want a * as a var, call the script like this:

./script.sh \*

Upvotes: 1

Related Questions