2017-08-16 95 views
1

嘿,我正在使用管道卷曲方法从帖子创建任务。当我使用硬编码值从终端运行时,它工作正常。但是,当我尝试用变量来执行它,它抛出一个错误:使用bash脚本解析curl中的变量

脚本:

#!/bin/bash 
echo "$1" 
echo "$2" 
echo "$3" 
echo "$4" 
echo "$5" 
echo '{ 
    "transactions": [ 
    { 
     "type": "title", 
     "value": "$1" 
    }, 
    { 
     "type": "description", 
     "value": "$2" 
    }, 
    { 
     "type": "status", 
     "value": "$3" 
    }, 
    { 
     "type": "priority", 
     "value": "$4" 
    }, 
    { 
     "type": "owner", 
     "value": "$5" 
    } 
    ] 
}' | arc call-conduit --conduit-uri https://mydomain.phacility.com/ --conduit-token mytoken maniphest.edit 

执行:

./test.sh "test003 ticket from api post" "for testing" "open" "high" "ahsan" 

输出:

test003 ticket from api post 
for testing 
open 
high 
ahsan 
{"error":"ERR-CONDUIT-CORE","errorMessage":"ERR-CONDUIT-CORE: Validation errors:\n - User \"$5\" is not a valid user.\n - Task priority \"$4\" is not a valid task priority. Use a priority keyword to choose a task priority: unbreak, very, high, kinda, triage, normal, low, wish.","response":null} 

正如你所看到的错误读取$ 4和$ 5作为值不变量。而且我无法理解如何在这些参数中使用$变量作为输入。

回答

1

您使用的是最后一个echo附近的单引号,以便您可以在JSON中使用双引号,但这会导致echo在不扩展任何内容的情况下打印字符串。您需要为该字符串使用双引号,因此您必须将其中的双引号转义。

将最后echo本:

echo "{ 
    \"transactions\": [ 
    { 
     \"type\": \"title\", 
     \"value\": \"$1\" 
    }, 
    { 
     \"type\": \"description\", 
     \"value\": \"$2\" 
    }, 
    { 
     \"type\": \"status\", 
     \"value\": \"$3\" 
    }, 
    { 
     \"type\": \"priority\", 
     \"value\": \"$4\" 
    }, 
    { 
     \"type\": \"owner\", 
     \"value\": \"$5\" 
    } 
    ] 
}" 

,它会工作。要避免这样的问题,您可以检查http://wiki.bash-hackers.orghttp://mywiki.wooledge.org/BashGuide,以获得bash新手的一些常规提示。此外,你可以使用shellcheck与许多文本编辑器,这会自动发现这样的错误。