简体   繁体   English

在/ bin / bash中使用的printf

[英]printf using in /bin/bash

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(OS X标准GNU bash版本3.2.57(1)-发行版(x86_64-apple-darwin15))中使用printf(C)2007自由软件基金会,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) 我想获取字符串“ 1.8.0_102”(截至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. 我想将字符串设置为红色,并且脚本将同时在OS X和Linux中运行,所以我不想使用echo。

Why can't I get 1.8.0_101 by printf? 为什么我不能通过printf获得1.8.0_101?

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? 所以$()输入到latest_version的变量工作不正确?

You can pipe your curl with awk to parse latest version: 您可以使用awk通过curl解析最新版本:

latest_version=$(curl -s http://java.com/en/download/installed8.jsp |
awk -F= '/latest8/{gsub(/^[^[:digit:]]*|\x27.*$/, "", $2); print $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. 您会看到多余的\\r (回车符)字符。

To fix this add the \\r to your tr command and that will work like a charm: 要解决此问题,请将\\r添加到您的tr命令中,它将像tr按钮一样工作:

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM