【问题标题】:bash unable to export the variable to scriptbash 无法将变量导出到脚本
【发布时间】:2019-12-06 07:00:07
【问题描述】:

我被我的代码卡住了,感谢您的帮助。这是我从詹金斯执行的一段代码。

#!/bin/bash
aws ec2 describe-instances --query 'Reservations[*].Instances[*].[Tags[?Key==`Name`].Value|[0],PrivateIpAddress]' --output text | column  | grep devtools > devtools
ip=`awk '{print $2}' devtool`
echo $ip

ssh ubuntu@$ip -n "aws s3 cp s3://bucket/$userlistlocation . --region eu-central-1"



cd builds/${BUILD_NUMBER}/
scp * ubuntu@$ip:/home/ubuntu


if [ $port_type == "normal" ]; then
if [ $duplicate_value == "no" ]; then
if [ $userlist == "uuid" ]; then
ssh ubuntu@$ip -n "export thread_size='"'$thread_size'"'; filename=$(echo $userlistlocation | sed -E 's/.*\/(.*)$/\1/') ; echo $filename ; echo filename='"'$filename'"'; chmod +x uuidwithduplicate.sh; ./uuidwithduplicate.sh"



fi
fi
fi
fi

userlistlocation --> 是一个用户输入,它可以是任何格式 /rahul/december/file.csv 或者只是它可以是 file.csv。

通过 sed 命令,我可以获得输出并存储在“文件名”变量中。

但是当我尝试 echo $filename 它打印为 echo $filename 它应该打印为 file.csv

这个 file.csv 将是另一个要运行的脚本的源文件,即 uuidwithduplicate.sh

userlistlocation 和 thread_size 都是通过 Jenkins 作业参数指定的。

我在导出 thread_size 时没有遇到问题,唯一的问题是文件名。

它只是打印 echo $filename --> 它应该打印 file.csv

【问题讨论】:

  • 在计算基本名称后执行echo ull="$userlistlocation" bn="$fbname"
  • 总是引用文件名:fbname=$( basename "$userlistlocation" )。但不确定,如果它在这里有帮助。

标签: linux bash shell ssh


【解决方案1】:

分解ssh 命令:

ssh ubuntu@$ip -n "export thread_size='"'$thread_size'"'; filename=$(echo $userlistlocation | sed -E 's/.*\/(.*)$/\1/') ; echo $filename ; echo filename='"'$filename'"'; chmod +x uuidwithduplicate.sh; ./uuidwithduplicate.sh"

进入单/双引号项目的段

  • “导出线程大小='”
  • '$thread_size'
  • "@'; filename=$(echo $userlistlocation | sed -E 's/./(.)$/\1/') ; echo $filename ; echo filename='@ "
  • '$文件名'
  • "'; chmod +x uuidwithduplicate.sh; ./uuidwithduplicate.sh"

注意:在第三个标记上,在双引号和单引号之间添加了一个“@”以使其更具可读性。不是命令的一部分。

表面上的几个问题:

  • '$thread_size' 应为 "$thread_size" 以启用扩展
  • 'echo $filename' 用双引号引起来,导致在本地主机上扩展,而设置 filename=$(echo ...) 在远程主机上执行。
  • 文件名有两个echo,不知道为什么

建议的解决方案是将filename的设置移动到本地主机(简化命令),并将thread_size移动到双引号中。可以将完整的命令放入单个双引号项中:

filename=$(echo $userlistlocation | sed -E 's/.*\/(.*)$/\1/')

ssh localhost -n "export thread_size='$thread_size'; echo '$filename' ; echo filename='$filename'; chmod +x uuidwithduplicate.sh; ./uuidwithduplicate.sh"

【讨论】:

  • 您能否提供更多详细信息、错误消息等。尝试在脚本中添加“set -x”。输出是什么?
  • 感谢您的解决方案,但没有奏效。当我按照你下面提到的方式执行时,我得到的输出是 ssh ubuntu@$ip -n "export thread_size='3'; echo '$filename' ; chmod +x uuidwithduplicate.sh; ./uuidwithduplicate.sh"部分是它能够打印 thread_size 变量但不能打印 $filename。整个脚本由单个用户运行。该用户能够选择 thread_size,它是 jenkins 中的(参数化)变量,但不能选择作为脚本一部分的变量($filename)
  • 你能在赋值后做 echo $filename=... 吗?
  • 很奇怪。您是从终端运行还是从 Jenkins 作业运行?它可以从终端工作吗?
  • 我正在逃避 Jenkins 的工作。 “通过 ssh 发送文件或执行命令”我将脚本保留在那里以供执行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-22
  • 2013-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-20
相关资源
最近更新 更多