function isaix { echo "alias d='du -sm -- * 2>/dev/null | sort -nr | head -20'" >> ~/.kshrc; }
function islinux { echo "alias d='du -sm -- * 2>/dev/null | sort -nr | head -20'" >> ~/.bash_profile; }
OSTYPE="`uname`"; if echo "${OSTYPE}" | grep -iq aix; then isaix; fi; if echo "${OSTYPE}" | grep -iq linux; then islinux; fi
前面的行创建了一个“d”别名,其中按大小列出了前 20 个文件和目录。
问题: 如何让这些长线变短? (操作系统类型检测或任何其他部分)
答案1
OSTYPE="`uname`"
OSTYPE="${OSTYPE,,}"
case "$OSTYPE" in
*aix*)
target=~/.kshrc
;;
*linux*)
target=~/.bash_profile
;;
esac
if [ -n "$target" ]; then
echo "alias d='du -sm -- * 2>/dev/null | sort -nr | head -20'" >> "$target"
fi
答案2
使用 shell 的命令扩展$(...)
来切换输出文件名。
此代码仅检查 aix。默认行为更新.bashrc
.
echo "alias d='du -sm -- * 2>/dev/null | sort -nr | head -20'" >> $( case $(uname) in *[aA][iI][xX]*) echo ~/.kshrc;; *) echo ~/.bashrc;; esac )
或者,为了可读性而分割线:
rcfile=$( case $(uname) in *[aA][iI][xX]*) echo ~/.kshrc;; *) echo ~/.bashrc;; esac )
echo "alias d='du -sm -- * 2>/dev/null | sort -nr | head -20'" >> $rcfile
答案3
更紧凑的版本(在 ksh 和 bash 中有效)是:
typeset -l ostype
ostype="$(uname)";
cmd="alias d='du -sm -- * 2>/dev/null |sort -nr |head -n 20'"
case "$ostype" in
*aix*) echo "$cmd" >> ~/.kshrc; ;;
*linux*) echo "$cmd" >> ~/.bash_profile; ;;
esac
答案4
一个更短的答案,但更神秘一些(适用于 bash 和 ksh):
typeset -l ostype; ostype="$(uname)"
cmd="alias d='du -sm -- * 2>/dev/null | sort -nr | head -20'"
case $ostype in
*linux*) a=ba;;
*aix*) a=k;;
esac
a="${a:+~/".${a}shrc"}"
${a:+false} || echo "$cmd" >> "$a"