我的个人资料里有这样的几行:
alias x='ls -al'; alias y='df -kh' # etc我有各种定义变量的行:
xx='name'; yy='stuff'如果我为别名做了一个错误,并且不把单词alias放在它前面,那么它只会定义一个变量,而不会生成一个错误,例如y='df -kh'。
是否有一种用grep或awk解析脚本的方法来查找所有在它们之前没有alias的定义(这样我就可以确定它们应该是别名还是变量声明)?也就是说,找到任何看起来像一个没有在前面写alias的变量的东西?
发布于 2022-06-06 11:32:20
$ cat defs
alias x='ls -al'; alias y='df -kh' # etc
xx='name'; yy='stuff'$ cat diffsets
#!/bin/bash
# Restart with a clean environment in case the file has been sourced
# previously. We need the absolute path in the shebang above for this.
[[ -v HOME ]] && exec -c "$0" "$@"
# We must use full paths without variables in case those variables
# are also set in the file we're about to source.
[[ -s "$1" ]] &&
mkdir -p "/usr/tmp/diffsets_$$" &&
trap '
rm -f "/usr/tmp/diffsets_$$/old" "/usr/tmp/diffsets_$$/new" &&
rmdir "/usr/tmp/diffsets_$$"
' 0 &&
# We want to only compare variables, not function definitions, but we
# can't use `set -o posix` as we need newlines printed as $'\n' instead
# of literal newline chars for later comparison so ensure posix is disabled
# and use awk to exit when the first function is seen as they always are
# printed after variables.
set +o posix &&
set | awk '$NF=="()"{exit} 1' > "/usr/tmp/diffsets_$$/old" &&
. "$1" &&
set +o posix &&
set | awk '$NF=="()"{exit} 1' > "/usr/tmp/diffsets_$$/new" &&
comm -13 "/usr/tmp/diffsets_$$/old" "/usr/tmp/diffsets_$$/new"$ ./diffsets defs
xx=name
yy=stuff我特别不使用变量来保存set输出以进行比较,也不使用mktemp来创建临时文件(这需要变量来保存mktemp输出),因为如果要源的文件(本例中的defs)包含这些变量的定义,那么使用该脚本中的变量的任何操作都会失败。
https://stackoverflow.com/questions/72512857
复制相似问题