简体   繁体   中英

When the argument of a function is an environment variable, how does GNU Bash handle it?

When I use $1 , passing $PATH to the function will only output the first line in the console:

format() {
  printf "%s\n" $1 | tr ":" "\n" | nl
}
$ format $PATH
        1 /Applications/Visual\

And when I change $1 to $@ , all content of $PATH can be output:

format() {
  printf "%s\n" $@ | tr ":" "\n" | nl
}
$ format $PATH
        1 /Applications/Visual\
        2   Studio\
...

I see that GNU Bash 's documentation says that $1 represents the first argument, and $@ represents all arguments (if multiple parameters are passed), but here I clearly pass only one argument $PATH , why use $@ to get all content of $PATH ?

GNU Bash is separating arguments by SPACES by default. $@ is used to capture all the arguments to function. Your PATH variable may have some paths which is having SPACES in it, which is causing your input argument to break into multiple strings separated by SPACE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM