簡體   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