Bash – Use asterisk in variables

bashescape-characterskshshell-scriptvariable

I want to cat all files to one new file in a bash script.

For example there are three files in my dir:
– file_a.txt
– file b.txt
– file(c).txt

When I write the following, it works without problems:

cat "file"*".txt" >> out_file.bak

No I want to make it more flexible/clean by using a variable:

input_files="file"*".txt"
cat $input_files >> out_file.bak

Unfortunately this doesn't work. The question is why? (When I echo input_files and run the command in terminal everything is fine. So why doesn't it work in the bash script?)

Best Answer

It depends when you want to do the expansion:

When you define the variable:

$ files=$(echo a*)
$ echo $files
a1 a2 a3
$ echo "$files"
a1 a2 a3

When you access the variable:

$ files=a*
$ echo "$files"
a*
$ echo $files
a1 a2 a3
Related Question