【发布时间】:2014-05-09 12:19:39
【问题描述】:
我有以下 .sh 文件,我从网上找到的东西拼凑而成。
目标是读取 CSV 文件中的第 2 行第 2 项,并使用它向 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"
【问题讨论】:
-
不要试图用字符串和变量组成命令。使用 函数.
-
你能详细说明一下吗?
-
@n.m.即使使用函数,在 shell 脚本中的某些时候,也经常需要将东西粘合在一起......这通常可以表明可能是时候考虑另一种语言,例如 python
-
写一个名为
query的函数。将$PROGRAMURL作为参数传递。 -
他仍然需要知道如何将随后变为
$1的内容加入到该函数内的其余参数-d...