在Ubuntu(Linux)的提示符上显示代码名称(小插曲)

修改命令提示符环境变量的\h,根据 lsb_release 的输出

提取 lsb_release -a 命令的代号的代码段。

lsb_release -a
#>No LSB modules are available.
#>Distributor ID: Ubuntu
#>Description:    Ubuntu 22.04.3 LTS
#>Release:        22.04
#>Codename:       jammy

lsb_release -a 2>/dev/null|grep 'Codename:' |perl -pe 's/^.+\s+([^\s]+)\s*$/$1/g'
#> jammy...

将其设置为变量的代码片段

DIST_CODENAME=`lsb_release -a 2>/dev/null|grep 'Codename:' |perl -pe 's/^.+\s+([^\s]+)\s*$/\$1/g'`

echo "$DIST_CODENAME"
#> jammy

只需将提示环境变量的主机名指定部分\h替换为变量$DIST_CODENAME并查看的代码片段。

echo "$PS1"
#> \[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\u@\h:\w\$

echo "$PS1"|perl -pe 's/\\h/'$DIST_CODENAME'/g'
#> \[\e]0;\u@jammy: \w\a\]${debian_chroot:+($debian_chroot)}\u@jammy:\w\$

把PS1替换为命令提示符并应用的代码片段

# 変更前のPS1をOLDPS1に退避
export OLDPS1="$PS1"
#engbjapan@localhost:~$  
export PS1=`echo "$OLDPS1"|perl -pe 's/\\\\h/'\$DIST_CODENAME'/g'`
#engbjapan@jammy:~$

把这些内容转化为脚本。

# ~/.chghost2codename に作成します
cat <<SEOF > ~/.chghost2codename
export OLDPS1="\$PS1"
DIST_CODENAME=\`lsb_release -a 2>/dev/null|grep Codename: |perl -pe 's/^.+\s+([^\s]+)\s*\$/\$1/g'\`
export PS1=\`echo "\$OLDPS1"|perl -pe 's/\\\\\\\h/'\$DIST_CODENAME'/g'\`
echo 'I changed the hostname of the prompt to the distribution codename.'
echo 'If you want to restore it, please execute the following command.'
echo 'export PS1="\$OLDPS1"'
SEOF
export OLDPS1="$PS1"
DIST_CODENAME=`lsb_release -a 2>/dev/null|grep Codename: |perl -pe 's/^.+\s+([^\s]+)\s*$/$1/g'`
export PS1=`echo "$OLDPS1"|perl -pe 's/\\\\h/'$DIST_CODENAME'/g'`
echo 'I changed the hostname of the prompt to the distribution codename.'
echo 'If you want to restore it, please execute the following command.'
echo 'export PS1="$OLDPS1"'

请重新登录以进行确认。

ssh localhost 
#>engbjapan@localhost's password:
#>Welcome to Ubuntu 22.04.3 LTS (GNU/Linux 3.13.0-00298-g3c7cbb9-#dirty armv7l)
#>
#> * Documentation:  https://help.ubuntu.com
#> * Management:     https://landscape.canonical.com
#> * Support:        https://ubuntu.com/advantage
#>Last login: Sat Dec  9 06:35:07 2023 from XXX.XXX.XXX.XXX
#>engbjapan@localhost:~$
source ~/.chghost2codename
# 若しくは`. ~/.chghost2codename`

#>I changed the hostname of the prompt to the distribution codename.
#>If you want to restore it, please execute the following command.
#>export PS1="$OLDPS1"
#>engbjapan@jammy:~$

如果要添加到登录shell

# 現在のログインシェルをバックアップ `~/.bashrc` の場合
cp -a ~/.bashrc ~/.bashrc`date +"%Y_%m_%d_%H_%M_%Sbk"`

echo 'source ~/.chghost2codename' >> ~/.bashrc

tail -5 ~/.bashrc
#>    . /etc/bash_completion
#>  fi
#>fi
#>export LANG=ja_JP.UTF-8
#>source ~/.chghost2codename
#>engbjapan@jammy:~$

 

广告
将在 10 秒后关闭
bannerAds