changing wsl ubuntu host name

126 阅读1分钟

操作指南

set /etc/wsl.conf

# newname=devink8s
newname=wsl
f=/etc/wsl.conf
# add file if does not exsit.
[ ! -e $f ] && touch $f


# txt="
# [network]
# hostname=$newname
# generateHosts = false
# "
# key=network;cat $f | grep "\[$key\]" > /dev/null 2>&1 ; [ $? -eq 1 ] && echo "$txt" >>  $f

# add [network] if does not exsit.
key=network;cat $f | grep "\[$key\]" > /dev/null 2>&1 ; [ $? -eq 1 ] && echo "[$key]" >> $f

# add hostname  if does not exsit.
cat $f | grep "hostname=" > /dev/null 2>&1 ; if [ $? -eq 0 ] ; then sed -iE "s/hostname=.*/hostname=$newname/g" $f ; else sed -i "s/\[$key\]/\[$key\]\nhostname=$newname/g"  $f ; fi

# echo "generateHosts = false" >> $f
cat $f | grep "generateHosts=" > /dev/null 2>&1 ; if [ $? -eq 0 ] ; then sed -iE "s/generateHosts=.*/generateHosts=false/g" $f ; else sed -i "s/\[$key\]/\[$key\]\ngenerateHosts=false/g"  $f ; fi


# change in /etc/hosts
oldname=`hostname` ; sed -i "s/$oldname/$newname/g" /etc/hosts
# oldname=DESKTOP-H1IKCEF ; sed -i "s/$oldname/$newname/g" /etc/hosts

# change in /etc/hostname 
echo "$newname" > /etc/hostname 

change in /etc/hosts

oldname=`hostname` ; sed -i "s/$oldname/$newname/g" /etc/hosts;
# oldname=DESKTOP-H1IKCEF ; sed -i "s/$oldname/$newname/g" /etc/hosts

change in /etc/hostname

echo "$newname" > /etc/hostname 

shutdown wsl

wsl --shutdown
# wsl -l -v

start wsl

wsl

check

hostname
cat /etc/hostname

cat /etc/hosts

cat /etc/wsl.conf

all in one

use case 1:

# or: ( will use default config)
curl -sfL https://ghproxy.com/https://raw.githubusercontent.com/ymc-github/wslubt-use-host-name/main/index.sh | sh

use case 2:

# only download index.sh file
curl -O https://ghproxy.com/https://raw.githubusercontent.com/ymc-github/wslubt-use-host-name/main/index.sh

# get  index.sh script usage
./index.sh -h

# get  index.sh script version
# ./index.sh -v

# zero:task:s:swicth-user
# if you do not have the rights to edit file /etc/apt/sources.list
# you can swicth user with su.
# su [options] [-] [<user> [<argument>...]]
# su - $USER
# zero:task:e:swicth-user

# use name wsl
./index.sh wsl

# use name zero
# ./index.sh wsl zero

use case 3:(recommended)

you can use as below ( including download , add-x-right , run-sh, and del-sh) .

# download -> add-x-right -> run-sh
todir=./tool/wslubt-use-host-name; tof="$todir/index.sh";uri=https://ghproxy.com/https://raw.githubusercontent.com/ymc-github/wslubt-use-host-name/main/index.sh;  mkdir -p "$todir"; curl -o "$tof" -s $uri; chmod +x "$tof"; "$tof" wsl; 

# del-sh:
# rm -rf "$todir";

file sample

/etc/wsl.conf

[boot]
systemd=true

[network]
hostname=wsl
generateHosts = false

wsl /etc/hostname

参考文献

changing wsl ubuntu host name

changing wsl ubuntu host name

change-ubuntu-wsl2-hostname-permanently