如何在 Bash 脚本中给变量赋空值

如何在 Bash 脚本中给变量赋空值

我正在尝试将 2 个仪表板导出到两个不同的文件中,在循环中,第一个仪表板 ID 正在读取,值正在存储 {ES_HOST1},然后 {ES_HOST1} 变为空,然后在循环中从数组中读取第二个仪表板。这里如何使 {ES_HOST1} 为空?如何在 bash 脚本中找到 {ES_HOST1} 数据类型?

#!/bin/bash
declare -a dashbords=(
"3f527fe0-dca4-11ea-966f-1555682d6680"
"02a44e70-eb68-11ea-8842-9727b4e7a447")

declare -a files=("file1" "file2")

#declare -a files=("file1" "file2" "file3")

ES_HOST="$(curl -s -X GET -u elastic:passwd http://noddde1:5601/s/sunstone/api/saved_objects/_find?type=dashboard)"
#echo ${ES_HOST}

for dashboard in ${dashbords[@]}
do
echo ${dashboard}
#for file in ${files[@]}
# do
ES_HOST1="$(curl -s -X POST -u elastic:passwd "http://noddde1:5601/s/sunstone/api/saved_objects/_export" -H "kbn-xsrf: true" -H "Content-Type: application/json" -d "
{
  \"objects\":
 [
    {
      \"type\": \"dashboard\",
      \"id\": \"${dashboard}\"
    }
  ]
}"
)"
echo ${ES_HOST1}
unset ${ES_HOST1}
echo ${ES_HOST1}
#echo ${ES_HOST1} >> ${file}.ndjson
#unset ${ES_HOST1} 
#done 
done

帮我写一个 bash 脚本。谢谢。

答案1

这应该可以让你到达你要去的地方:

#!/usr/bin/env bash

dashbords=(
"3f527fe0-dca4-11ea-966f-1555682d6680"
"02a44e70-eb68-11ea-8842-9727b4e7a447")

for dashboard in ${dashbords[@]} ; do
  dashboardvar=$(echo $dashboard | tr '-' '_') # hyphens not allowed in var names
  declare hostname_${dashboardvar}=${dashboard}-hostname-007 # Including dashbaord in example hostname just for some diff outputs. Replace with your curl cmd.
done

echo -e "3f527fe0-dca4-11ea-966f-1555682d6680 hostname: $hostname_3f527fe0_dca4_11ea_966f_1555682d6680"
echo -e "02a44e70-eb68-11ea-8842-9727b4e7a447 hostanme: $hostname_02a44e70_eb68_11ea_8842_9727b4e7a447"

# These can now be written to files, etc.

该脚本输出以下内容:

3f527fe0-dca4-11ea-966f-1555682d6680 hostname: 3f527fe0-dca4-11ea-966f-1555682d6680-hostname-007
02a44e70-eb68-11ea-8842-9727b4e7a447 hostanme: 02a44e70-eb68-11ea-8842-9727b4e7a447-hostname-007

下面是我个人的片段备忘单中关于此类变量处理的一个例子,它解释了其工作原理。

#!/usr/bin/env bash
# Example of Bash Indirection for dynamic variable construction

# Constructed/dynamic reference vars
foo_color=red
bar_color=blue

echo -e "\nConstructed/Bash Indirection Vars:"
for i in foo bar ; do
  # Construct vars for use in the loop
  #   See: BASH Indirection (kind of like a dictionary lookup)
  varname=${i}_color
  color=${!varname}
  echo $color

  # Declare dynamically named variables for use outside of thie loop
  declare color_${i}=$color

done

echo -e "\nDeclared Variables"
echo $color_foo
echo $color_bar

该脚本输出以下内容:

Constructed/Bash Indirection Vars:
red
blue

Declared Variables
red
blue

相关内容