繁体   English   中英

在bashrc中仅使用一次别名

[英]use alias only once in bashrc

我在.bashrc文件中写了一个别名,每次启动bash shell时都会打开一个txt文件。 问题是我只想打开一次这样的文件,那是我第一次打开外壳。

有什么办法吗?

解决此问题的一般方法是拥有某种会话锁。 您可以使用正在编辑其他文件的进程的pid和/或tty创建文件/ tmp / secret,并在完成后删除锁定文件。 现在,应该将其他会话设置为不创建该文件(如果已存在)。

正确锁定是一个复杂的主题,但是对于简单的情况,这可能就足够了。 如果没有,谷歌的“互斥”。 请注意,如果弄错了,可能会带来安全隐患。

为什么要为此使用别名? 听起来代码应该直接放在您的.bashrc中,而不是别名定义中。

所以,如果说, .bashrc现在有什么类似

alias start_editing_my_project_work_hour_report='emacs ~/prj.txt &̈́'
start_editing_my_project_work_hour_report
unalias start_editing_my_project_work_hour_report

...然后加上锁定,并且没有别名,您可能最终会得到类似

# Obtain my UID on this host, and construct directory name and lock file name
uid=$(id -u)
dir=/tmp/prj-$uid
lock=$dir/pid.lock

# The loop will execute at most twice,
# but we don't know yet whether once is enough
while true; do
  if mkdir -p "$dir"; then
     # Yay, we have the lock!
     ( echo $$ >"$lock" ; emacs ~/prj.txt; rm -f "$lock" ) &
     break

  else
     other=$(cat "$lock")

     # If the process which created the UID is still live, do nothing
     if kill -0 $other; then
       break
     else
       echo "removing stale lock file dir (dead PID $other) and retrying" >&2
       rm -rf "$dir"
       continue
     fi
  fi
done

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM