Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wildcard expansion in bash script

Tags:

bash

if I write this string in my script:

list=$(ls /path/to/some/files/*/*/*.dat)

it works fine. But what I need is

files="files/*/*/*.dat"
list=$(ls /path/to/some/${files})

and it says

ls: /path/to/some/files/*/*/*.dat: No such file or directory

How should I do it?

like image 796
Morse Avatar asked Jul 27 '12 11:07

Morse


People also ask

What is a wildcard in bash?

Much like how in cards games a wild card can be used as a substitute for any other card in the deck, in bash, wildcard characters can be used to substitute for any other character in the alphabet (including numerals and symbols). The technical term for this substitution is called an expansion.

What is wildcard expansion?

Wildcard argument expansion is Microsoft-specific. When you run a C program, you can use either of the two wildcards, the question mark ( ? ) and the asterisk ( * ), to specify filename and path arguments on the command line. By default, wildcards aren't expanded in command-line arguments.

What is a * symbol in Linux wildcard?

The wildcard '*' means it will match any number of characters or a set of characters. For example, S**n will match anything between S and n. The number of characters between them do not count.

Why does the shell need to expand wildcards?

If any wildcards weren't expanded by the shell (either because they failed to match or because they were escaped by the user) they will be passed to this second invocation of BusyBox. If busybox.exe were to expand these wildcards in might result in unexpected behaviour.


1 Answers

If you only get that message where there truly are no matching .dat files, add this to your script:

shopt -s nullglob

It will cause the glob to expand to an empty list if there are no matching files, rather than being treated literally.

like image 164
chepner Avatar answered Nov 08 '22 12:11

chepner