简体   繁体   English

在bashrc中仅使用一次别名

[英]use alias only once in bashrc

I wrote an alias in my .bashrc file that open a txt file every time I start bash shell. 我在.bashrc文件中写了一个别名,每次启动bash shell时都会打开一个txt文件。 The problem is that I would like to open such a file only once, that is the first time I open the shell. 问题是我只想打开一次这样的文件,那是我第一次打开外壳。

Is there any way to do that? 有什么办法吗?

The general solution to this problem is to have a session lock of some kind. 解决此问题的一般方法是拥有某种会话锁。 You could create a file /tmp/secret with the pid and/or tty of the process which is editing the other file, and remove the lock file when done. 您可以使用正在编辑其他文件的进程的pid和/或tty创建文件/ tmp / secret,并在完成后删除锁定文件。 Now, your other sessions should be set up to not create this file if it already exists. 现在,应该将其他会话设置为不创建该文件(如果已存在)。

Proper locking is a complex topic, but for the simple cases, this might be good enough. 正确锁定是一个复杂的主题,但是对于简单的情况,这可能就足够了。 If not, google for "mutual exclusion". 如果没有,谷歌的“互斥”。 Do note that there may be security implications if you get it wrong. 请注意,如果弄错了,可能会带来安全隐患。

Why are you using an alias for this? 为什么要为此使用别名? Sounds like the code should be directly in your .bashrc, not in an alias definition. 听起来代码应该直接放在您的.bashrc中,而不是别名定义中。

So if, say, what you have now in your .bashrc is something like 所以,如果说, .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

... then with the locking, and without the alias, you might end up with something like ...然后加上锁定,并且没有别名,您可能最终会得到类似

# 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