Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins can't access shell alias

I have configured a Jenkins job to source a bash script that sources another bash script which adds an alias to the .bashrc of its user and sources the .bashrc itself, and then original script tries to use that alias (set by the second). However, it cannot seem to find the alias it has just created. I am not using any scripting plugins aside from using a "Send files or execute commands over SSH" build step to source the script.

The job does this:

source ./test_script.sh

test_script.sh looks like this:

echo "In test_script.sh"
echo $USER
echo $HOME
source ./setup_env.sh
echo "\nBack in test_script.sh"
alias foo
foo

And finally, setup_env.sh looks like this:

echo "\nIn setup_env.sh"
echo "alias foo=\"echo foobar\"" >> $HOME/.bashrc
source $HOME/.bashrc 2>/dev/null
cat $HOME/.bashrc

The output I receive from the Jenkins job looks like this:

In test_script.sh
my_user
/home/my_user
\nIn setup_env.sh
...all of my bashrc...
alias foo="echo foo"
\nBack in test_script.sh
alias foo='echo foo'
./test_script.sh: line 7: foo: command not found

I don't understand why this is happening, when I can happily run it myself on the command-line and watch it succeed. Why can't Jenkins use the new alias, when it can obviously find it (as demonstrated by the output of the alias foo command)?

like image 750
Daniel Brady Avatar asked Aug 02 '13 14:08

Daniel Brady


2 Answers

For anyone else who's having this problem, you may need to set the expand_aliases shell option, which seems to be off by default with Jenkins:

shopt expand_aliases # check if it's on
shopt -s expand_aliases # set expand_aliases option to true
shopt expand_aliases # it should be on now

# test with a simple alias, should print 1
alias x="python -c 'print 1'"
x
like image 141
Galen Long Avatar answered Oct 01 '22 14:10

Galen Long


The \n that is showing in the output of your echo commands
suggest this is not running under bash, as you may be expecting.

Please check the setting of your jenkins user
(or any other user that you run Jenkins with) -
especially the setting of the default shell.

To test this, add one of those lines at the beginning of your script:

env

or

env | grep -i shell

Should also consider making sure your scripts run under the correct shell,
by adding the "shebang" line as the first line in each script.
In the case of 'bash', for example, you should add the following first line:

#!/bin/bash

(it is not a comment, despite what the auto-syntax-highlighter may think...)

like image 40
Gonen Avatar answered Oct 01 '22 13:10

Gonen