在 macOS 移除 .NET Core 較為麻煩

由於 Microsoft 所提供的 .NET Core SDK 安裝檔是 pkg 格式,優點是安裝很方便,只要下一步下一步就好,但缺點是移除時比較麻煩。

Vervion


macOS High Sierra 10.13.3
.NET Core SDK 2.1.4

下載 .NET Core Uninstall Script


dotnet-uninstall-pkgs.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/env bash
#
# Copyright (c) .NET Foundation and contributors. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.
#

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

current_userid=$(id -u)
if [ $current_userid -ne 0 ]; then
echo "$(basename "$0") uninstallation script requires superuser privileges to run" >&2
exit 1
fi

# this is the common suffix for all the dotnet pkgs
dotnet_pkg_name_suffix="com.microsoft.dotnet"
dotnet_install_root="/usr/local/share/dotnet"
dotnet_path_file="/etc/paths.d/dotnet"
dotnet_tool_path_file="/etc/paths.d/dotnet-cli-tools"

remove_dotnet_pkgs(){
installed_pkgs=($(pkgutil --pkgs | grep $dotnet_pkg_name_suffix))

for i in "${installed_pkgs[@]}"
do
echo "Removing dotnet component - \"$i\"" >&2

pkgutil --force --forget "$i"
done
}

remove_dotnet_pkgs
[ "$?" -ne 0 ] && echo "Failed to remove dotnet packages." >&2 && exit 1

echo "Deleting install root - $dotnet_install_root" >&2
rm -rf "$dotnet_install_root"
rm -f "$dotnet_path_file"
rm -f "$dotnet_tool_path_file"

echo "dotnet packages removal succeeded." >&2
exit 0

此為 .net core 官方所提供的 uninstall script

16 行

1
dotnet_pkg_name_suffix="com.microsoft.dotnet"

mac002

只要是 com.microsoft.dotnet 開頭的 package,都是 .net core 所安裝。

21 行

1
2
3
4
5
6
7
8
9
remove_dotnet_pkgs(){
installed_pkgs=($(pkgutil --pkgs | grep $dotnet_pkg_name_suffix))

for i in "${installed_pkgs[@]}"
do
echo "Removing dotnet component - \"$i\"" >&2
pkgutil --force --forget "$i"
done
}

將所有 com.microsoft.dotnet 為開的 package 名稱儲存為 installed_pkgs 陣列。

installed_pkgs 陣列內 package 一一 for 執行,使用 pkgutil —force —forget 移除 package。

35 行

1
2
3
rm -rf "$dotnet_install_root"
rm -f "$dotnet_path_file"
rm -f "$dotnet_tool_path_file"
  • 刪除 /usr/local/share/dotnet 目錄
  • 刪除 /etc/paths.d/dotnet 檔案
  • 刪除 /etc/paths.d/dotnet-cli-tools 檔案

有此可見,要乾淨移除 .NET Core SDK,必須包含 :

  1. 移除所有 com.microsoft.dotnet 為首的 package
  2. 刪除 /usr/local/share/dotnet 目錄
  3. 刪除 /etc/paths.d/dotnet/etc/paths.d/dotnet-cli-tools 檔案

執行 .NET Core Uninstall Script


1
$ sudo sh ./dotnet-uninstall-pkgs.sh

mac000

測試 .NET Core SDK


1
$ dotnet --version

mac001

若出現 command not found ,表示 .NET Core SDK 已經成功移除。

Conclusion


  • 只要是 pkg 格式的安裝檔,理論上都要原廠提供 反安裝檔,或者 uninstall script,才能徹底的乾淨移除,而不能只是將檔案拖到 垃圾桶 而已

Reference


.NET Foundation, dotnet-uninstall-pkgs.sh

2018-02-06