首页 > 解决方案 > 从文本文件读取的 Bash 脚本变量不起作用

问题描述

在脚本中,我尝试将会话令牌字符串分配给变量,该令牌字符串存储在文本文件中。

SESSION_TOKEN=$(<login_token.txt)

以前,我通过字面写作来完成作业。

SESSION_TOKEN_ORIGINAL=eyJhbGciOiJI......CGHyYuRs 

由于每次启动会话时会话令牌都不同,因此我将获得的令牌存储在文本文件中,而不是每次都编辑 bash 脚本。

出乎意料的是,SESSION_TOKEN 没有被服务器接受,而 SESSION_TOKEN_ORIGINAL 工作。

我使用 bash 调用脚本

bash ./myscript.bash

为了理解原因,我创建了一个实验比较语句

if [ "$SESSION_TOKEN" == "$SESSION_TOKEN_ORIGINAL" ]
then
    echo "two tokens are the same"
fi

它不输出相等的语句。为什么?

为了更好地说明上下文,我发布了整个脚本,并屏蔽了服务器地址。

#!/bin/bash
SESSION_TOKEN=$(<./login_token.tmp)
SESSION_TOKEN_ORIGINAL=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkdXIiOjI
USERID=fsag25fea
curl -s -X GET -H "x-tidepool-session-token: $SESSION_TOKEN" -H "Content-Type: application/json" "https://api.database.org/metadata/users/$USERID/users"  #this does not work, the server responds with 0 content
curl -s -X GET -H "x-tidepool-session-token: $SESSION_TOKEN_ORIGINAL" -H "Content-Type: application/json" "https://api.database.org/metadata/users/$USERID/users"  #this works, the server responds with the expected json

标签: bash

解决方案


推荐阅读