问题描述
我在Jenkins Execute shell块中有一个如下编写的bash脚本
id="233"
我想在以下命令中使用此id变量
bash -c 'comm -12 <(sort file1_${id}.txt) <(sort file2_${id}.txt)'
但是会引发错误
sort: cannot read: file1_.txt: No such file or directory
sort: cannot read: file2_.txt: No such file or directory
我尝试了以下操作,但是没有运气,也不知道如何解决
"$id"
"${id}"
'$id'
'${id}'
解决方法
单引号阻止$id
在bash
运行之前被扩展,并且变量id
没有在外壳中定义,然后在外壳程序中扩展$id
尝试。
简单(但易碎)的解决方案是使用双引号,以便$id
扩展以生成要在新shell中运行的命令。
bash -c "comm -12 <(sort file1_${id}.txt) <(sort file2_${id}.txt)"
一种更健壮的解决方案是将$id
的值作为参数传递给shell(并在命令中使用双引号 来保护$1
的扩展, $id
的值是否需要)。
bash -c 'comm -12 <(sort "file1_$1.txt") <(sort "file2_$1.txt")' bash "$id"
(脚本后的第一个参数用于设置$0
;它的值无关紧要,但是shell的名称是一个很好的伪参数。)
(由于某些原因,我假设需要bash -c '...'
,并且您不能简单地单独使用comm -12 <(sort "file1_$id.txt") <(sort "$file2_$id.txt")
。)
bash -c 'comm -12 <(sort file1_'$id'.txt) <(sort file2_'$id'.txt)'
以上行现在有效