Search code examples
bashmacosfunctioncommand-substitution

Is there a way to display function output in bash command


Have a simple bash script I am working on with Mac, but I am having one issue.

#!/bin/bash

# Pull users IP from getifaddr on specfic port
myip ( ) {
    #ipconfig getifaddr ppp0
    local _ip _myip _line _nl=$'\n'
    while IFS=$': \t' read -a _line ;do
        [ -z "${_line%inet}" ] &&
           _ip=${_line[${#_line[1]}>4?1:2]} &&
           [ "${_ip#127.0.0.1}" ] && _myip=$_ip
      done< <(LANG=C /sbin/ifconfig)
    printf ${1+-v} $1 "%s${_nl:0:$[${#1}>0?0:1]}" $_myip
}

printf "My ip: %" 
myip

# Static server IP stored
serverip ( ) {
    echo 192.168.12.110

}


serverip

## Command to add them together
sudo route add $myip $severip

So far the functions work, but the sudo route command does not since I am guessing there is no return value.

What I need it to do it output the myip IP address and the serverip IP address onto the line so the command can run in a single command.

For example: sudo route add 192.168.0.1 192.168.0.2

Right now, it tells me "myip is not a valid routing address" as I believe it is taking the literal 4 character string "myip" and not the IP address.


Solution

  • Bash's command substitution might help:

    sudo route add $(myip) $(serverip)