如何用变量替换脚本中的用户名

Fix*_*xeR 9 command-line bash scripts

我想为我的家用 PC 制作一个安装脚本,我想让它更灵活。

如何用当前用户变量替换我的用户名?

示例:下载到:/home/THISUSER/Downloads/

dad*_*x86 21

您可以将变量$HOME用于家庭和$USER用户。

您的示例可以是$HOME/Downloads/home/$USER/Downloads

  • 并非所有系统都使用 /home 作为主目录,因此最佳做法是在引用主目录时使用 $HOME。 (10认同)
  • 仅仅因为这个站点只关于 Ubuntu 并不意味着你应该避免编写可移植的代码和使用最佳实践。 (4认同)
  • @asmeurer 我们只处理 Ubuntu 和官方衍生产品。哪个默认版本不使用 /home? (3认同)

Rin*_*ind 15

如果你想这样做,你应该使用......

more ~/.config/user-dirs.dirs
# This file is written by xdg-user-dirs-update
# If you want to change or add directories, just edit the line you're
# interested in. All local changes will be retained on the next run
# Format is XDG_xxx_DIR="$HOME/yyy", where yyy is a shell-escaped
# homedir-relative path, or XDG_xxx_DIR="/yyy", where /yyy is an
# absolute path. No other format is supported.
# 
XDG_DESKTOP_DIR="/discworld/Desktop"
XDG_DOWNLOAD_DIR="/discworld/Downloads"
XDG_TEMPLATES_DIR="/discworld/Templates"
XDG_PUBLICSHARE_DIR="/discworld/Public"
XDG_DOCUMENTS_DIR="/discworld/Documents"
XDG_MUSIC_DIR="/discworld/Music"
XDG_PICTURES_DIR="/discworld/Pictures"
XDG_VIDEOS_DIR="/discworld/Videos"
Run Code Online (Sandbox Code Playgroud)

所以那将是

echo $(xdg-user-dir DOWNLOAD)
Run Code Online (Sandbox Code Playgroud)

它将显示默认下载位置(在我的情况下/discworld/Downloads)。适用于所有这些词。喜欢 ...

echo $(xdg-user-dir DESKTOP)
Run Code Online (Sandbox Code Playgroud)