bash - All files in one dir, linux -


today tried script in linux files in 1 dir. pretty straightforward, found interesting.

 #!/bin/bash inputdir=/home/xxx/ file in $inputdir'*'   echo $file done 

the output is:

/home/xxx/filea /home/xxx/fileb  

but when input dir directly, like:

 #!/bin/bash inputdir=/home/xxx/ file in /home/xxx/*   echo $file done 

the output is:

/home/xxx/filea /home/xxx/fileb 

it seems, in first script, there 1 loop , file names stored in variable $file in first loop, separated space. in second script, 1 file name stored in $file in 1 loop, , there more 1 loop. difference between these 2 scripts?

thanks much, maybe question little bit naive..

the behavior correct , "as expected".

for file in $inputdir'*' means assign "/home/xxx/*" $file (note quotes). since quoted asterisk, not executed @ time. when shell sees echo $file, first expands variables , glob expansion. after first step, sees

echo /home/xxx/* 

and after glob expansion, sees:

echo /home/xxx/filea /home/xxx/fileb 

only now, execute command.

in second case, pattern /home/xxx/* expanded before for executed , thus, each file in directory assigned file , body of loop executed.

this work:

for file in "$inputdir"* 

but it's brittle; fail, example, when forget add / end of variable $inputdir.

for file in "$inputdir"/* 

is little bit better (unix ignore double slashes in path) can cause trouble when $inputdir not set or empty: you'll list files in / (root) folder. can happen, example, because of typo:

inputdir=... file in "$inputdir"/* 

case matters on unix :-)

to understand code this, use set -x ("enable tracing") in line before code want debug.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -