我正在使用带有一些内联 Python 的 Bash 脚本来读取 JSON API。我取出一小部分输出并将其转储到临时文件中。我知道临时文件存在,因为我能够head
对其运行操作。但是,当需要实际迭代文件中的行时,我收到如下错误read: /tmp/temporary_tag_storage.H9hEH6': not a valid identifier
以下是我的脚本的完整相关部分:
#!/usr/bin/env bash
getTagByNumber () {
SOMETHING=$(curl -s 'https://localhost:8000/api/tagstubs' | \
python3 -c "import sys, json; print(json.load(sys.stdin)[$1]['tag'])")
echo "$SOMETHING" >&3
}
TAGNUMBER=0;
tmpfile=$(mktemp /tmp/temporary_tag_storage.XXXXXX)
# create file descriptor 3 for writing to a temporary file so that
# echo ... >&3 writes to that file
exec 3>"$tmpfile"
# create file descriptor 4 for reading from the same file so that
# the file seek positions for reading and writing can be different
exec 4<"$tmpfile"
while [ $TAGNUMBER -lt 5 ]
do
getTagByNumber $TAGNUMBER $TAGS
TAGNUMBER=$(( $TAGNUMBER + 1 ))
done
#This works, dutifully spitting out five lines of text.
head -n $TAGNUMBER <&4
#So why does this give me "not a valid identifier"?
while read $tmpfile; do
echo "$p"
done
#rm "$tmpfile"
...输出如下:
politics
sports
religion
film
television
./createtags.sh: line 83: read: `/tmp/temporary_tag_storage.H9hEH6': not a valid identifier
如您所见,第一次尝试读取标签成功,输出了一堆主题名称。这就是为什么我对第二次while
循环失败感到困惑。
我尝试$tmpfile
在第二个循环的定义中用双引号括住变量名while
,但这似乎没有帮助。
有谁知道我做错了什么?