0

I'm working on a script to retrieve the serial number from a host running OS X, and then append the number to the end of a URL.

#!/bin/bash
# Retrieve serial number in OS X, then append serial number to URL

### Retrieve serial number ###

function serial_number(){
    local serialnum=$(system_profiler SPHardwareDataType | awk '/Serial/ {print $4}')
    # Use system_profiler to poll info, then print 4th column of Serial from SPHardwareDataType

    # write_header "Serial Number"
    echo "${serialnum}"
    echo ""
}

### Append serial number to URL ###

function apple_link(){
    local appleurl=$"https://support.apple.com/specs/${serialnum}"
    echo "${appleurl}"
    echo ""
}

### Testing ###
apple_link

I get this as a result: https://support.apple.com/specs/, which does not show the appended serial number. I'm not entirely sure why this is? Any comments or suggestions on how to "fix" my oversight would be greatly appreciated. Thanks in advance.

marshki
  • 607
  • 1
  • 4
  • 14
  • It would be better to present a script with the absolutely minimum commands necessary to reproduce the issue. In your case I think it should be about 4 lines long. – ndemou Feb 08 '17 at 15:52
  • There is a function serial_number which is never called, a local variable serialnumand a reference to serial_num; seems weird – ridgy Feb 08 '17 at 15:54
  • You are right. That was a typo on my part. – marshki Feb 08 '17 at 16:37

1 Answers1

1

You have one function that outputs a serial number and another that outputs an URL. To combine the two outputs:

url="$(apple_link)$(serial_number)"

Or, in the apple_link function:

local appleurl="https://support.apple.com/specs/$(serial_number)"

The $( ... ) will be expanded to the output of the command.

The only thing to change apart from that is to remove the echo "".

If you want to do it properly:

serial_number () {
  system_profiler SPHardwareDataType | awk '/Serial/ { print $4 }'
}

apple_link () {
  printf 'https://support.apple.com/specs/%s\n' "$( serial_number )"
}

Notice that there's no need to use any variables anywhere, or to echo anything. The printf is there because it's a safer alternative to echo. See Why is printf better than echo?

Kusalananda
  • 333,661
  • This is most helpful. The use of variables was done b/c these functions are part of a larger script that outputs the results to the user. I'm not sure if that makes a difference. As to echo vs. pritnf: I appreciate the guidance. – marshki Feb 08 '17 at 19:42