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

六眼飞鱼酱① 提交于 2019-12-02 07:23:47

问题


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.


回答1:


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:

  • Difference between single and double quotes in Bash
  • What is the benefit of using $() instead of backticks in shell scripts?



回答2:


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`


来源:https://stackoverflow.com/questions/48552087/using-a-command-that-needs-backticks-to-be-passed-as-part-of-an-argument-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!