为什么我还在用 macOS Mojave ?

为什么会写这样一篇文章,得从今天一个 GitHub 的 Issue 说起:

今天中午收到我之前在 Karabiner-Elements 提的一个 issue (How can I press the shortcut key and use Google to search for the selected content? #2535) 的 回复。打开后一看,这个问题我已经解决了,他遇到了,那我就帮帮他看看。经过一番答复,最终我得知是由于他使用最新的 macOS Big Sur 导致 open 命令不能打开带有中文的链接,除非中文进行 URL 编码

看来我的稳定升级系统是非常理智的。我现在是一个比较追求稳定的人,包括 macOS 的更新提醒,我是不会随便更新的,每次都会先查查该升级是否存在问题,若有影响我使用的问题,我是不会升级的。
别说我守旧啊😱😱😱,我也会用另一台非生产力的 Mac 升级体验最新特性。

其实这篇文章主要是讲下我如何解决 Big Sur 下 open 命令不能打开带有中文的链接的问题。

问题

这里我不重复复述,想看我们讨论的详情,请看 (How can I press the shortcut key and use Google to search for the selected content? #2535

在 Big Sur 11.3.1 下 open 命令不能打开带有中文的链接,使用如下命令即可复现:

1
2
ganzhixiong@ganzhixiongdeMacBook-Pro-2 ~ % open 'https://www.google.com/search?q=abc123你好'
The file /Users/ganzhixiong/https:/www.google.com/search?q=abc123你好 does not exist.

原因

在苹果开发者论坛中 BigSur: open command not handling file URI scheme properly 页面最后一个回复找到了原因。

原因就是 URL 中使用了中文字符导致,如果要含有中文,需要对中文进行 URL 编码。
我想着应该是 Big Sur 的一个 Bug 吧,我看还是叫 Bug Sur 吧😡😡😡!

解决

通过 URL 编码搜索关键字即可解决。

我没有找到 Shell 编码的方法,但是我找到了 Python URL 编码的方法,由于 macOS 自带 Python,因此该方法可行,该命令如下:

1
open "https://www.google.com/search?q=$(python -c "import urllib, sys; print urllib.quote(sys.argv[1])"  "abc123你好")"

当然也有其他方法用于 URL 编码,我找到了三种方法,分别是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# ganzhixiong @ ganzhixiongdeMacBook-Pro-3 in ~/Documents/blog [22:01:30] 
$ echo $data
abc123你好

# 方法一,使用 perl。
# ganzhixiong @ ganzhixiongdeMacBook-Pro-3 in ~/Documents/blog [22:01:34]
$ echo $(perl -MURI::Escape -e 'print uri_escape($ARGV[0]);' "$data")
abc123%E4%BD%A0%E5%A5%BD

# 方法二,使用 Python3。
# ganzhixiong @ ganzhixiongdeMacBook-Pro-3 in ~/Documents/blog [22:02:38]
$ echo $(python3 -c "import urllib.parse, sys; print(urllib.parse.quote(sys.argv[1]))" "$data")

abc123%E4%BD%A0%E5%A5%BD

# 方法三,使用 Python。
# ganzhixiong @ ganzhixiongdeMacBook-Pro-3 in ~/Documents/blog [22:03:27]
$ echo $(python -c "import urllib, sys; print urllib.quote(sys.argv[1])" "$data")
abc123%E4%BD%A0%E5%A5%BD

其中方法一,使用 perl 的性能最高。

参考

为什么我还在用 macOS Mojave ?

https://ganzhixiong.com/p/9dd93282/

Author

干志雄

Posted on

2021-09-08

Updated on

2021-09-08

Licensed under

Comments