我有以下.sh文件,我把我在互联网上发现的东西拼凑在一起 目标是读取CSV文件中的第二行第二项,并使用它来向elasticsearch发送删除命令。
#!/bin/sh
OLDIFS=$IFS
IFS=,
function quit {
echo "Quitting Script"
IFS=$OLDIFS
exit 1
}
function fileExists {
if [ ! -f "$1" ]
then
echo "File $1 does not exists"
quit
fi
echo "File Name: $1"
}
function work {
linesToSkip=1
{
for ((i=$linesToSkip;i--;)) ;do
read
done
#Read 2nd item of the 2nd line of CSV file to get PROGRAMURL
read INDEX PROGRAMURL JUNK
echo "$PROGRAMURL"
QUERY="curl -XDELETE http://127.0.0.1:9200/cj/_query -d '{ \"query\" : { \"match\" : { \"PROGRAMURL\" : "$PROGRAMURL" } } }'"
$("$QUERY")
#RESPONSE=`$QUERY`
#echo $RESPONSE
} < $1
}
fileExists $1
work $1
IFS=$OLDIFS
除了curl脚本的执行外,一切都有效。我用$(),backtics,exec尝试过,我无法让它工作。
以下是运行bash -vx script.sh时的错误:
bash -vx ./deleteExisting.sh catalog.csv
#!/bin/sh
OLDIFS=$IFS
+ OLDIFS='
'
IFS=,
+ IFS=,
function quit {
echo "Quitting Script"
IFS=$OLDIFS
exit 1
}
function fileExists {
if [ ! -f "$1" ]
then
echo "File $1 does not exists"
quit
fi
echo "File Name: $1"
}
function work {
linesToSkip=1
{
for ((i=$linesToSkip;i--;)) ;do
read
done
#Read 2nd item of the 2nd line of CSV file to get PROGRAMURL
read INDEX PROGRAMURL JUNK
echo "$PROGRAMURL"
QUERY="curl -XDELETE http://127.0.0.1:9200/cj/_query -d '{ \"query\" : { \"match\" : { \"PROGRAMURL\" : "$PROGRAMURL" } } }'"
$("$QUERY")
#RESPONSE=`$QUERY`
#echo $RESPONSE
} < $1
}
fileExists $1
+ fileExists catalog.csv
+ '[' '!' -f catalog.csv ']'
+ echo 'File Name: catalog.csv'
File Name: catalog.csv
work $1
+ work catalog.csv
+ linesToSkip=1
+ (( i=1 ))
+ (( i-- ))
+ read
+ (( 1 ))
+ (( i-- ))
+ read INDEX PROGRAMURL JUNK
+ echo '"http://www.website.com"'
"http://www.website.com"
+ QUERY='curl -XDELETE http://127.0.0.1:9200/cj/_query -d '\''{ "query" : { "match" : { "PROGRAMURL" : "http://www.website.com" } } }'\'''
"$QUERY")
"$QUERY"
++ 'curl -XDELETE http://127.0.0.1:9200/cj/_query -d '\''{ "query" : { "match" : { "PROGRAMURL" : "http://www.website.com" } } }'\'''
./deleteExisting.sh: line 29: curl -XDELETE http://127.0.0.1:9200/cj/_query -d '{ "query" : { "match" : { "PROGRAMURL" : "http://www.website.com" } } }': No such file or directory
IFS=$OLDIFS
+ IFS='
'
示例CSV文件将是
INDEX, PROGRAMURL, other, info
"1", "http://website.com", "other info", "information"
答案 0 :(得分:7)
正在运行$("$QUERY")
尝试在子shell中运行,这个命令名为<the expanded value of $QUERY>
,因此导致'(bunch of stuff) No such file or directory'
错误。
您可能需要以下内容:
CURLURL="http://127.0.0.1:9200/cj/_query"
CURLDATA='{ "query" : { "match" : { "PROGRAMURL" : "'$PROGRAMURL'" } } }'
RESPONSE=`curl -XDELETE "$CURLURL" -d "$DATA"`
这里的技巧是如何嵌套单引号和双引号。有点难以简明扼要地解释,但这里有:
$PROGRAMURL
扩展到上面,立即将它连接在一对封闭开放的单引号之间。CURLDATA
,必须将其传递给双引号内的curl
命令VARIABLE1="Hello, world"
VARIABLE2='This is "$verbatim" stuff"'$VARIABLE1'" More stuff'
$VARIABLE2
This is "$verbatim" stuff"Hello, World" More stuff
其他注意事项:
curl
命令的整个标准输出放入变量RESPONSE
$?
以查看curl是否真的设法与主持人交谈等等 - 如果一切顺利,它将为0 跳过行:
tail -n +$(( $linesToSkip +1 ))