Mailinglist Archive: opensuse (880 mails)

< Previous Next >
Re: [opensuse] Back to the basics (bash)
On 8/11/2013 5:04 PM, Ciro Iriarte wrote:
Hi!, anybody can tell me why using "[]" sustitution for file listing works

ciro@roamer:/tmp> ls -ld [123]b
drwxr-xr-x 2 ciro users 4096 ago 10 16:22 1b
drwxr-xr-x 2 ciro users 4096 ago 10 16:22 2b
drwxr-xr-x 2 ciro users 4096 ago 10 16:22 3b

But for file creation it doesn't?

ciro@roamer:/tmp/bash> mkdir [123]dir
ciro@roamer:/tmp/bash> touch [123].file
ciro@roamer:/tmp/bash> ls -l
total 4
drwxr-xr-x 2 ciro users 4096 ago 11 17:04 [123]dir
-rw-r--r-- 1 ciro users 0 ago 11 17:04 [123].file


[123] is a globbing pattern like * is.
Globbing only expands to existing files that match the pattern, if any.
If only one or two of the possible files exist, then the pattern will only expand to those one or two files, not all 3. If none exist then no expansion or substitution occurs and you get the literal string [123].

In the case of creating new files, since they may or may not exist, or maybe some exist and not all, you don't want globbing, you want string manipulation.

You want to be able to write some kind of shorthand that expands to the final string you want, as a plain string manipulation, not trying to find any existing files.

mkdir {1,2,3}dir
touch {1,2,3}.file

Note these are all somewhat shell specific. These are simple enough that they work in pretty much any version of bash no matter how old, but may not work in some other shells like ash used in initrd's or dsh (debian) or /bin/sh on other unix systems besides linux.

Also note that it's up to you to verify that commands like mkdir and touch can even take multiple target arguments at the same time on one command line. They both can, at least on linux, so these commands would work. But in other cases, or if the expanded list were longer than about 4kb, you would have to learn about xargs.

Also use echo to test potentially risky expansions like this to make sure it will do what you think it will do before you let real commands actually try to do stuff.

dev1:oh7:~ $ echo [123]foo
dev1:oh7:~ $ echo {1,2,3}foo
1foo 2foo 3foo


To unsubscribe, e-mail: opensuse+unsubscribe@xxxxxxxxxxxx
To contact the owner, e-mail: opensuse+owner@xxxxxxxxxxxx

< Previous Next >
Follow Ups