3

I have a bash script like below. Near table variable I want to use backticks like in my script.

#!/bin/bash

[ $# -ne 2 ] && { echo "Usage : $0  database table "; exit 1; }

database=$1
table=$2

hive -e "alter table ${database}.`${table}` SET TBLPROPERTIES('EXTERNAL'='FALSE')"

This above script gives me below error

script.sh: line 10: table: command not found

But if I don't use backticks near table variable then the script works fine.

But I need to have backticks near table variable. How can I do that?

I have tried like below as well

hive -e "alter table ${database}.$(table) SET TBLPROPERTIES('EXTERNAL'='FALSE')"

I still got the same error.

U880D
  • 8,601
  • 6
  • 24
  • 40
User12345
  • 5,180
  • 14
  • 58
  • 105

2 Answers2

4

Inside double quotes, backticks are being interpreted by shell, resulting in table being treated as a command. You need to escape them:

hive -e "alter table ${database}.\`${table}\` SET TBLPROPERTIES('EXTERNAL'='FALSE')"

Alternatively, you can use a variable to hold the backticks:

bt="\`"
hive -e "alter table ${database}.$bt${table}$bt SET TBLPROPERTIES('EXTERNAL'='FALSE')"

The issue with your second command

hive -e "alter table ${database}.$(table) SET TBLPROPERTIES('EXTERNAL'='FALSE')"

is that the construct $(table) works the same way as table inside backticks - it is just a better way of doing command substitution in Bash. Hence you get the same error as earlier.


Related posts:

codeforester
  • 39,467
  • 16
  • 112
  • 140
0

Backticks in BASH (and other shells) cause the string inside the backticks to be run as a program. The output of the program is then pasted into the command in place of the backticks.

$ echo "it is now `date`"
it is now Wed Jan 31 17:01:28 EST 2018

One solution is to use single quotes instead of double quotes:

$ echo 'it is now `date`'
it is now `date`

However, in your command you want values like ${database} to be evaluated, and single quotes prevent that kind of evaluation as well. So your best bet is to use backslash to escape the backticks:

$ echo "it is now \`date\`"
it is now `date`
A. L. Flanagan
  • 1,162
  • 8
  • 22
  • 1
    One can mix multiple quoting types inside a single command or argument. ```echo 'it is now`'"$(date)"'`'``` is perfectly valid: The backticks are literal because they're in single quotes, the `$()` gets expanded because it's in double quotes. – Charles Duffy Jan 31 '18 at 22:09
  • Great point. Bash syntax is ... amazing. (baroque?) (strange?) – A. L. Flanagan Jan 31 '18 at 22:12