SoWhat
SoWhat

Reputation: 5622

Shell script doesn't change to directory passed as parameter

I am making a sort of a deployment script. Its a very simple git pull based deployment. I need it to accept two parameters: the app to be deployed and the type of server(staging, testing, production). So I wrote the script with a function for each app

./deploy.sh <appname> <server>

--

#deploy.sh
app1(){
        echo $2 #Empty
        cd /srv/www/app1/$2 #


        git pull origin master

}
case $1 in
        "app1") app1;;
esac

Now when I run the script with the following command ./deploy.sh app1 staging. The script only navigates to the /srv/www/app1 directory, not /srv/www/app1/staging When I echo $2, nothing is displayed. What am I doing wrong?

Upvotes: 0

Views: 151

Answers (2)

zzzirk
zzzirk

Reputation: 1592

Look into scope. Each function a shell script can be passed arguments. The app() function is looking for $2 as an argument to itself. There have been no args passed, so $2 equates to "". If you use the script below you should be fine, passing $2 to app1 in the case.

#deploy.sh
app1(){
        echo $1 #Empty
        cd /srv/www/app1/$1 #


        git pull origin master

}
case $1 in
    "app1") app1 $2 ;;
esac

Upvotes: 0

Ashish Gaur
Ashish Gaur

Reputation: 2050

The problem is when you use $2 in app1 it tries to interpret the arguments passed to app1 which is empty, so you need to pass it as an argument to app1. Try this:

app1(){
        echo $1 #Empty
        cd /srv/www/app1/$1 #


        git pull origin master

}
case $1 in
        "app1") app1 $2;;
esac

Upvotes: 2

Related Questions