samedi 30 août 2014

Beware of command substitution in bash

It's dangerous to use a loop with ls results in your bash scripts:

for i in $(ls)

Unix/Linux allows for almost any character in file names, including new lines and spaces. Then, what happens when there's a file with a space in its name:

╭─mansuro@localhost  ~/workspace/new_dir 
╰─$ touch some\ file
╭─mansuro@localhost  ~/workspace/new_dir  
╰─$ ls
some file
╭─mansuro@localhost  ~/workspace/new_dir  
╰─$ (for i in $(ls); do echo $i; done)


 As you can see, the file was treated as two different arguments, and that would have undesirable effects in your bash scripts.
How can we fix this? We could change 

for i in $(ls)


for i in *

╭─mansuro@localhost  ~/workspace/learning/Terminal/new_dir  
╰─$ (for i in *; do echo $i; done) 

some file

And you're done, your bash script works the way you want it to.

Aucun commentaire:

Enregistrer un commentaire