LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash if statement (https://www.linuxquestions.org/questions/programming-9/bash-if-statement-475567/)

noir911 08-20-2006 05:04 AM

Bash if statement
 
I have a program which SSH me to different servers and server name is taken as a command line argument ($ARG1). All servers are in port 22 but only 1 in a different port. I want to make the code such that if I type that server name it will connect me that server and for everything else it will connect me to port 22.

But it is not working since I added the function for the different port server in the if-statement.

Here's the code

Code:

server23()
{
    ssh -p 600 me@server
}

if [ -f $PASSWD_FILE ]; then
  if [ $1 = server23 ]; then
      server23
else
grep $1 $PASSWD_FILE
ssh username@$1
    fi
fi


druuna 08-20-2006 05:40 AM

Hi,

Too bad you don't tell us what is going wrong. Looking at the code I see some things that are incorrect or could be improved.

This should work, using your original idea:
Code:

#!/bin/bash

server23()
{
  ssh -p 23 username@$SERVER
}

SERVER="$1"

if [[ -f $PASSWD_FILE ]]; then
  if [[ $SERVER == "server23" ]]; then
    server23
  else
    grep $SERVER $PASSWD_FILE
    ssh username@$SERVER
  fi
fi

But the above can be done a lot simpler:
Code:

#!/bin/bash

SERVER="$1"
PORT="22"
[[ ${SERVER} == "server23" ]] && PORT="23"
ssh -p ${PORT} username@${SERVER}

Hope this helps.

jschiwal 08-20-2006 05:43 AM

You could have a variable called "port" with a default value of 22. Then test if this is the server with a different port. If so, assign a different number to the port and then use the line "ssh -p $port me@server".


All times are GMT -5. The time now is 05:56 PM.