在shell-script中使用字符串中的变量

时间:2018-03-26 16:23:55

标签: linux bash shell

我的变量没有被shell脚本中的值替换:

#!/bin/bash
read -p "Enter uuid "  uuid
read -p "Enter date in format yyyymmdd: " date

echo $uuid
echo $date

a=`zgrep 'Queue for uuid $uuid' reader_$date.gz`    
b=`zgrep 'Queue for uuid 23fef66b-fcf0-4a71-8ca3-a0761dffc473' reader_$date.gz`

echo $a
echo $b

输出:

Enter uuid 23fef66b-fcf0-4a71-8ca3-a0761dffc473                                         
Enter date in format yyyymmdd: 20180323
23fef66b-fcf0-4a71-8ca3-a0761dffc473
20180323

[2018-03-23 17:27:10,535: INFO/Worker-1 None None tasks/push_to_rabbit] Queue for uuid 23fef66b-fcf0-4a71-8ca3-a0761dffc473 is 35.154.190.22_2_k_event

为什么变量a为空?

2 个答案:

答案 0 :(得分:2)

您需要双引号,其中应扩展参数,而不是单引号。

错误引用:

u=23; d=3; a=$(zgrep 'Mar $u 23' /var/log/syslog.$d.gz); echo $a

右引言:

u=23; d=3; a=$(zgrep "Mar $u 23" /var/log/syslog.$d.gz); echo $a
Mar 23 23:00:01 tux201t CRON[25808]: (stefan) CMD ....

答案 1 :(得分:2)

用双引号替换单引号以允许bash变量替换。

a=`zgrep 'Queue for uuid $uuid' reader_$date.gz`

a=`zgrep "Queue for uuid $uuid" reader_$date.gz`