-1

Lets consider a bash variable which contains the name (file.txt) of a directory which is wildcarded:

var1='/home/user/file*'

and a variable with the full name var2='/home/user/file.txt'.

Now if I do echo $var1 it correctly prints file.txt. Now I want to call a programm from shell which uses var1 as one of the arguments. While using var2 works fine, just replacing it with var1 does not do an expansion. Irrelevant on how I give the arguments to said function, how can I make a copy var3 of var1 which is completely identical to var2, i.e. how can I force that expansion before handing the variable to the function?

Mark
  • 209
  • 3
  • 8
  • Your underlying assumptions are probably incorrect but without seeing the code which doesn't work we can't really help correct them. Please show us what you tried, and explain what you expected it to do. – tripleee Dec 07 '19 at 18:18
  • @Mark : I don't see in your post where you are passing the variables to the program you are mentioning. You can make a copy `var3=$var1`, but note that your whole approach breaks down if you have more than one matching file, for instance `file.txt` and `filer.txt`. A better way would be to use arrays, `var1=(/home/user/file*)`, and then verify whether the array has indeed only one element (in which case you can do a `var3=${var1[0]}`. – user1934428 Dec 08 '19 at 08:41

1 Answers1

1

Bash will perform wildcard expansion for unquoted variables. Assuming that you defined a pattern in a variable (like var1='PATTERN') you can force expansion by placing it outside any quotes:

function foobar {
   echo ARGS="$@"
}

var1='/home/user/file*'
foobar $var1

In the above example, foobar will be called with all matching files, each as separate argument. You can replace foobar with external command. Same effect.

Forcing expansion into other variables is a little bit more tricky and risky. Assuming the pattern source is trusted, one can use:

var1='/home/user/file*'
set -- $var1
var3=$*
dash-o
  • 13,723
  • 1
  • 10
  • 37