can anyone here tell me why the * is not passed to the bash shell script?

My script named as top40 is

 sudo du -shx $1 | sort -rh | head -n 40

when I try to run it as top40 /var/* the * is ignored. It is like top40 /var but I want to see the top 40`s size of the directories.

when I do it whithout script and type it on the prompt, it works fine.

I really can not find the reason for this. Thanks for opening my eyes. I use Ubuntu 18.04 LTS

  • Wildcards are expanded before your script is called. (You'll find that $2, $3 etc are defined.) – Ulrich Schwarz Mar 25 at 13:42
  • 1
    Change $1 to "$@". – jordanm Mar 25 at 13:47
  • @jordanm thanks a lot! – Walter Schrabmair Mar 25 at 13:50

This is basic shell expansion. Because the calling shell recognizes the * as a wildcard character, it's actually interpreting that for you, and passing a list of all the items in /var/ to your script.

If you escape the wildcard, or quote the wildcard to prevent it from being expanded in the calling shell, it will pass to your script the way you expect it to.

Here are two examples that will probably do what you want if my understanding of your intent is correct.

  • /path/to/script.sh '/var/run/*'
    • this example prevents shell interpretation by putting the asterisk in a single quoted string, which bypasses expansion and gets passed as-is to the script.
  • /path/to/script.sh /var/run/\*
    • this example just escapes the single asterisk character from shell expansion.

Both of these examples result in the string /var/run/* being passed AS-IS, to your script where they become $1.

  • 1
    Thank you - I learnt a lot with your answer. – Walter Schrabmair Mar 25 at 14:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.