0

I have a command that works fine and looks like this:

bq query --use_legacy_sql=false --format json --batch=true 'select * from `ga4-extract.analytics_123456789.events_20220722` limit 1;' > data.json

I would like to make this part of the command 20220722 a variable.

export rundate="20220722"

Tried just:

bq query --use_legacy_sql=false --format json --batch=true 'select * from `ga4-extract.analytics_123456789.events_$rundate` limit 1;' > data.json

This ran the command without variable substitution.

I read this similar post but it looks like it's more about manipulating a string rather than an entire command. Nevertheless, from that post I tried swapping single for double quotes:

bq query --use_legacy_sql=false --format json --batch=true "select * from `ga4-extract.analytics_123456789.events_$rundate` limit 1;" > data.json
bash: ga4-extract.analytics_302644320.events_20220722: command not found

Is it possible to swap out a variable within a command, as opposed to within a string? What's the 'right' way to do what I'm trying to achieve?

Doug Fir
  • 19,971
  • 47
  • 169
  • 299
  • 1
    If input is trusted, you can replace `$rundate` in the query by `'"$rundate"'`. If input is untrusted, don't subsitute unless you have carefully sanitised against injection attacks. – jhnc Jul 30 '22 at 19:18
  • single-quoted strings are not expanded by the shell. double-quoted strings are. Inside double-quoted strings, backticks are an old way of writing `$(...)` which executes the command given inside. – jhnc Jul 30 '22 at 19:20
  • 1
    in some queries, you can do substitution like: https://cloud.google.com/bigquery/docs/parameterized-queries#bq – jhnc Jul 30 '22 at 19:25
  • Thanks! That 3rd comment could help me here and now, but I'd like to know how to do this in unix more generally, for example I tried your first suggestion with: `bq query --use_legacy_sql=false --format json --batch=true 'select * from `ga4-extract.analytics_123456.events_'"$rundate'"` limit 1;' > data.json` and the console seems stuck, it's been like this for ten mins after submitting the query which usually runs in single digit seconds – Doug Fir Jul 30 '22 at 19:33
  • 2
    not `'"$rundate'"`, `'"$rundate"'`. you need to match up start/end of single/double quoting. with the command you show in your comment, your console is waiting for the end of a backtick command – jhnc Jul 30 '22 at 19:41

0 Answers0