2

Related: Stop shell wildcard character expansion?

I had in the past used set -f in bash to prevent glob expansion - however this seems to not work on my mac any more:

$ cat script.sh
#!/bin/bash

echo $0

i=1
for var in $@
do
    echo "$i => $var"
    ((i++))
done

$ set -f
$ ./script.sh *
./script.sh
1 => program
2 => program.cpp
3 => script.sh

With the set -f I expected the output to be

$ ./script.sh *
./script.sh
1 => *

What am I missing and how can I stop the expansion.

Aleks G
  • 56,435
  • 29
  • 168
  • 265

1 Answers1

1

You are running the script in a separate shell (running ./script.sh forks a sub-shell) than the one you actually set the option set -f on. Try putting it inside the script so it runs with the option set,

$ ./script.sh *
./script.sh
1 => *

Or you can source the script in the current shell as below with the set option applied.

$ set -f
$ source script.sh *
/usr/bin/bash
1 => *

See this cross-site reference What is the difference between executing a Bash script vs sourcing it? which provides some nice insight into the problem we are dealing here.

Inian
  • 80,270
  • 14
  • 142
  • 161