简体   繁体   English

使用需要反引号作为bash中参数的一部分传递的命令

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

I have a bash script like below. 我有一个如下的bash脚本。 Near table variable I want to use backticks like in my script. table变量我想在脚本中使用反引号。

#!/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. 但是我需要在table变量附近添加反引号。 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. 我仍然遇到相同的错误。

Inside double quotes, backticks are being interpreted by shell, resulting in table being treated as a command. 在双引号内,shell将解释反引号,从而将table视为命令。 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. $(table)构造与反引号内的table具有相同的工作方式-这只是在Bash中执行命令替换的一种更好的方式。 Hence you get the same error as earlier. 因此,您将得到与之前相同的错误。


Related posts: 相关文章:

Backticks in BASH (and other shells) cause the string inside the backticks to be run as a program . BASH(和其他shell)中的反引号导致反引号内的字符串作为程序运行 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. 但是,在您的命令中,您希望对$ {database}之类的值进行求值,并且单引号也会阻止这种求值。 So your best bet is to use backslash to escape the backticks: 因此,最好的选择是使用反斜杠来避免反引号:

$ echo "it is now \`date\`"
it is now `date`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM