2

I use printf in /bin/bash (OS X standard GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin15) Copyright (C) 2007 Free Software Foundation, Inc.

#!/bin/bash latest_version=\ $((curl -s http://java.com/en/download/installed8.jsp 2>/dev/null || wget -q -O - http://java.com/en/download/installed8.jsp) | grep 'latest8' |sed -E "s/.*= //" |tr -d "';") echo $latest_version printf "%s \n" $latest_version 

I want to get a string "1.8.0_102" (as of 2016/7/24)

This shows

#echo 1.8.0_101 #printf 8.0_101 

I want to make the string in red and the script will be run in both OS X and linux, so I do not want to use echo.

Why can't I get 1.8.0_101 by printf?

Further more what is wrong with this below?

printf "Get the latest Java \033[1;31m %s \033[m from Oracle.\n" $latest_version 

It also does not work...

I have a hint... when I put

latest_version=1.8.0_101 

then it works.

so the variable input to latest_version by $() is working wrong?

3
  • In the meanwhile I found a shorter solution: latest_version=$((curl -s http://java.com/en/download/installed8.jsp 2>/dev/null || wget -q -O - http://java.com/en/download/installed8.jsp) | grep latest8 | cut -f 2 -d\') Commented Jul 24, 2016 at 11:19
  • 1
    The grep, sed, tr pipe should be a single sed command: sed -n "/latest8/{s/.*= //;s/[';\r]//g;p}" Commented Jul 24, 2016 at 12:28
  • 1
    Or sed -n "/latest8/s/.*'\([^']*\)'.*/\1/p" Commented Jul 24, 2016 at 12:49

2 Answers 2

2

If you execute:

printf "%q \n" $latest_version 

you get:

$'1.8.0_101\r' 

and you can see the redundant \r (carriage returns) character.

To fix this add the \r to your tr command and that will work like a charm:

latest_version=$((curl -s http://java.com/en/download/installed8.jsp 2>/dev/null || wget -q -O - http://java.com/en/download/installed8.jsp) | grep 'latest8' |sed -E "s/.*= //" |tr -d "';\r") printf "%s \n" $latest_version 

outputs:

1.8.0_101 
Sign up to request clarification or add additional context in comments.

3 Comments

@hek2mgl I prefer to answer the OP question with the least modifications to his code so he can understand easily what went wrong
I understand the problem now. Thank you. But how can you see if we have \r in the latest_version in my expression.
As I wrote, use printf "%q \n" $latest_version
2

You can pipe your curl with awk to parse latest version:

latest_version=$(curl -s http://java.com/en/download/installed8.jsp | awk -F= '/latest8/{gsub(/^[^[:digit:]]*|\x27.*$/, "", $2); print $2}') 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.