LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   bash for strange expansion (https://www.linuxquestions.org/questions/linux-newbie-8/bash-for-strange-expansion-4175528590/)

doru 12-17-2014 03:14 PM

bash for strange expansion
 
Code:

touch a b a\(c\)b
$ ls *\(c\)*
a(c)b
$ for a in *\(c\)*; do ls $a; done
a(c)b
# this is ok
rm a\(c\)b
$ ls *\(c\)*
ls: cannot access *(c)*: No such file or directory
$ for a in *\(c\)*; do ls $a; done
a  b
# this is not clear. please tell me why would this happen?!


smallpond 12-17-2014 03:37 PM

Does this give you the behavior you expect?
Code:

shopt -s nullglob

doru 12-17-2014 04:28 PM

Quote:

Originally Posted by smallpond (Post 5286516)
Does this give you the behavior you expect?
Code:

shopt -s nullglob

Yes it does, thank you for your answer.
Why would be ls inconsistent with for, and why would *\(c\)* expand to the list of files as one word? I should be able to understand it by myself starting from here.

jpollard 12-17-2014 04:35 PM

Looks like you deleted the file.

suicidaleggroll 12-17-2014 04:40 PM

Put quotes around your variable in the for loop, same as you would if there's a space or any other "bad" character.

Code:

$ touch a b
for a in *\(c\)*; do ls $a; done
a  b
$ for a in *\(c\)*; do ls "$a"; done
ls: cannot access *(c)*: No such file or directory

same as this
Code:

$ touch "a b"
$ ls *\ *
a b
$ for a in *\ *; do ls $a; done
ls: cannot access a: No such file or directory
ls: cannot access b: No such file or directory
$ for a in *\ *; do ls "$a"; done
a b

If there's ever a chance you're going to have a character that requires delimiting (-, (, space, etc.) stored inside a variable, then you need to stick quotes around it when you use it.

doru 12-18-2014 02:34 PM

Sorry to bother you again, but please tell me why does this happen. () should introduce some subshell which here should result in an error.
Code:

$ ls *()*
a  a(c)b  a(c)c  b
$ ls *()
ls: cannot access *(): No such file or directory
$ ls ()*
bash: syntax error near unexpected token `('
$


doru 12-18-2014 02:48 PM

Quote:

Originally Posted by doru (Post 5287068)
Sorry to bother you again, but please tell me why does this happen. () should introduce some subshell which here should result in an error.
Code:

$ ls *()*
a  a(c)b  a(c)c  b
$ ls *()
ls: cannot access *(): No such file or directory
$ ls ()*
bash: syntax error near unexpected token `('
$


OK, so *() is some pattern matching in pathname expansion. So bash is looking for some file with a void name? OK, so nothing matches nothing, that's right. I did fall into a succession of traps here, did I not? Thank you all, :)


All times are GMT -5. The time now is 12:54 AM.