在Travis-CI中采购.bashrc无法正常工作

时间:2019-07-10 16:07:25

标签: linux bash shell travis-ci

最近几天,我一直在尝试为我的bash脚本项目设置Travis-CI构建。我在将别名粘贴到生活在Travis构建中而不是进行采购的.bashrc中时遇到问题。

下面是我在Linux上的.bashrc文件中创建bash别名并且尝试失败的简单示例。

Travis-CI(.travis.yaml):

language: bash

git:
  quiet: true
  submodules: false

matrix:
  include:
    - os: linux
      dist: xenial

script:
  - sh test_bash.sh || travis_terminate 1;
  - bash test_sourcing.sh || travis_terminate 1;

test_bash.sh:

current_shell=$(echo $SHELL)
if [ "$current_shell" != "/bin/bash" ]; then
    echo "The current build is not working with the Bash Shell."
    exit 1
fi 

test_sourcing.sh

alias name='echo "John Doe"' >> $HOME/.bashrc
source $HOME/.bashrc
output=$(name)
if [ "$output" != "John Doe" ]; then
    echo "Sourcing is not working for some reason."
    exit 1
fi 

从构建输出中得到的内容如下:

$ bash -c 'echo $BASH_VERSION'
3.2.57(1)-release
0.02s$ sh test_bash.sh || travis_terminate 1;
The command "sh test_bash.sh || travis_terminate 1;" exited with 0.
$ bash test_sourcing.sh || travis_terminate 1;
test_sourcing.sh: line 3: name: command not found
Sourcing is not working for some reason.

我希望所有测试都能通过,但是我很难理解这样一个简单的功能。我唯一能想到的是BASH的版本是不支持别名的版本。感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可以使用简单变量或通过eval执行它们,这与您想要的类似。

寻找name2以及带有和不带有eval的两个选项。 name1是您的代码。

$ cat test_sourcing.sh
set -x
alias name1='echo "John Doe"' >> $HOME/.bashrc
name2='echo "John Doe"' >> $HOME/.bashrc
source $HOME/.bashrc
output=$($name1)
output=$($name2)
output=$(eval $name2)
if [ "$output" != "John Doe" ]; then
    echo "Sourcing is not working for some reason."
    exit 1
fi

运行脚本时,您可以看到:

$ ./test_sourcing.sh
++ alias 'name1=echo "John Doe"'
++ name2='echo "John Doe"'
++ source /home/schroen/.bashrc
+++ case $- in
+++ return
++ output=
+++ echo '"John' 'Doe"'
++ output='"John Doe"'
+++ eval echo '"John' 'Doe"'
++++ echo 'John Doe'
++ output='John Doe'
++ '[' 'John Doe' '!=' 'John Doe' ']'
  • 第一个输出为空,因为别名没有扩展(如chepner说的那样)
  • 第二个输出设置为“ John Doe”,但直接运行echo。 (注意变量值内的"
  • 第3个输出也设置为“ John Doe”,但通过运行回显的eval进行设置。有时在与其他变量一起构建变量名时,这一点很重要。

eval件事...

$ cat variable-loop.sh
#!/usr/bin/env bash
#set -x

dev1=foo
dev2=bar
dev3=foobar

echo 'without eval not what we want...'
for i in $(seq 1 3); do
        echo dev$i
        echo $dev$i
done

echo 'with eval it is working...'
for i in $(seq 1 3); do
        eval echo \$dev$i
done

$ ./variable-loop.sh 
without eval not what we want...
dev1
1
dev2
2
dev3
3
with eval it is working...
foo
bar
foobar