简体   繁体   中英

Bash, assigning glob to a variable

I'm confused why expanding a variable which is assigned a value of glob preserves the literal white spaces upon it's expansion.

# Test 1
Tuomas@DESKTOP-LI5P50P MINGW64 ~/shell
$ files=$(ls)

Tuomas@DESKTOP-LI5P50P MINGW64 ~/shell
$ args $files
12 args: <11914> <21771> <29904> <6496> <8807> <a> <b> <c> <d> <e> <test1/> <test2/>

# Test 2
Tuomas@DESKTOP-LI5P50P MINGW64 ~/shell
$ files=*

Tuomas@DESKTOP-LI5P50P MINGW64 ~/shell
$ args $files
11 args: <11914> <21771> <29904> <6496> <8807> <a> <b> <c> <d e> <test1> <test2>

I would suppose in either assignments the variable ends up being a string, which the following expansion would split up to words on the white spaces (being unquoted). Apparently this isn't case in the glob test. What mechanism preserves the literal white spaces on the variable during it's expansion? Does the glob assignment implicitly make it as an array type? As far as I know, there are only string, array and integer types in the bash shell. I also know, that word splitting always takes place after parameter expansion.

Word splitting takes place after parameter expansion and before filename expansion . Until filename expansion, the argument is * , and that is what passes through word-splitting (obviously with no effect, since it contains no whitespace).

This is why you should (almost) always use * instead of $(ls) .

Assign the files to an array:

files=(*)

And use the array:

echo "${files[@]}"

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