User12345
User12345

Reputation: 5480

Using a command that needs backticks to be passed as part of an argument in bash

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.

Upvotes: 3

Views: 2510

Answers (2)

codeforester
codeforester

Reputation: 42999

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:

Upvotes: 5

A. L. Flanagan
A. L. Flanagan

Reputation: 1168

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`

Upvotes: 0

Related Questions