好的,我已经编写了一个 shell 脚本来读取具有以下格式的文件:
快捷方式1 /路径/到/目录1
快捷方式2 /路径/到/目录2
并且它应该读取文件并构建别名,以便将快捷方式1 cd 输入到映射目录中。问题是,循环中设置的任何别名都不会在脚本之外持续存在。
首先,我尝试只运行脚本。
. ./build_shortcuts.sh "~/.shortcuts"
其中文件 ~/.shortcuts 包含
dl ~/下载
音乐 /music
dtop ~/桌面
这没有用。然后我尝试在循环之外设置一些别名。如别名 hello='world'; 别名世界='hellob'。我重新运行脚本,输入别名以获取别名列表,它确实包含 hello 和 world 作为别名,但不包含循环中设置的任何别名。
然后我想也许循环根本没有设置它们,所以我在脚本中添加了别名作为最终命令,这样它就会在最后打印出别名;在这种情况下,它确实包含别名,但它们仍然没有保留在我的会话中。
build_shortcuts.sh
script="$(cat $@ | sed -r -e 's/#[A-Za-z0-9 ]*$//' -e '/^\s+/s/^\s+//' -e '/^\s*$/d' -)"
# strip comments, entry level indentation & empty lines (in that order) from filestream
echo "${script}" | while read shortcut; do
cut=$(echo "${shortcut}" | awk '{ print $1 }')
dest=$(echo "${shortcut}" | awk '{ $1=nil; print $0 }')
dest="${dest:1}" # trim leading whitespace character
alias "${cut}" &>/dev/null
if [ $? = 0 ]; then
echo "Warning: shortcut \"${cut}\" already exists" >&2
continue # by default, skip overwriting shortcuts
fi
echo alias ${cut}="'cd ${dest}'"
alias "${cut}"="'cd ${dest}'"
done
我希望脚本内循环中设置的别名存在于脚本之外。目前他们没有。
我在 arch linux 上运行“GNU bash,版本 5.0.7(1)-release (x86_64-pc-linux-gnu)”。
从Bash 手册页(关于Pipelines的部分):
管道中的每个命令都作为一个单独的进程执行(即在一个子 shell 中)
由于循环是作为管道的一部分完成的,它将是一个子外壳,并且您在子外壳中执行的别名命令只会为该子外壳设置。
一种可能的解决方法是将别名保存到列表中,然后alias
在第二个循环中执行实际命令,该循环不是管道或子外壳的一部分。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句