Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delaying wildcard expansion in bash, while quoting for special characters

I've written a bash script that needs to do something later. It's called something like this:

later mv *.log /somewhere/else

However, when called like this *.log is expanded at call time, and the script is called as if I wrote

later mv 1.log 2.log 3.log /somewhere/else

I'm trying to get my script to expand wildcards later. I tried calling it like this

later mv '*.log' /somewhere/else

and also with \*, but these both result in the wildcard never getting expanded at all.

How do I expand the wildcards in the commandline? And is there a way to prevent expansion when the script is called, i.e. get the original parameters as they were typed?

This is the part of my scripts that prepares the call for later:

tmpfile=$(mktemp)

### Get a quoted commandline
line=
while (( "$#" > 0 )); do
        line="$line\"$1\" "
        shift
done

### Prepare a script to be run
echo '#!/bin/bash' > "$tmpfile"
echo "cd $(pwd)" >> "$tmpfile"
echo "trap 'rm \"$tmpfile\"' EXIT" >> "$tmpfile"
echo "$line" >> "$tmpfile"
chmod 777 "$tmpfile"

Note that I have to quote the commandline as some of my files and folders have spaces in their names; if I remove the quoting bit, even bits without wildcards stop working.

like image 557
configurator Avatar asked Aug 03 '12 00:08

configurator


1 Answers

Interesting question. I suspect that a better answer than mine is possible. Nevertheless, given

A='foo.*'

this seems to do what you want:

echo $(eval echo "$A")
like image 163
thb Avatar answered Oct 30 '22 03:10

thb