【问题标题】:How to fix PATH recognition in Linux Bash如何修复 Linux Bash 中的 PATH 识别
【发布时间】:2021-02-11 00:50:50
【问题描述】:

我一直在寻找如何避免一个正在运行的程序的多个实例。

我无法在我的脚本中执行 cat 或 rm:

第 19 行:cat:找不到命令

第 21 行:rm:找不到命令

【问题讨论】:

  • 你的PATH 好像搞砸了。
  • 这很奇怪:您的系统找不到catrm(两者都存在于/usr/bin,但不会抱怨kill(存在于同一目录中) . 你能检查这些命令的目录并相应地编辑你的问题吗?(which <command>)
  • @Dominique 我不认为它曾经运行过kill,因为完成kill 命令行(包括cat)的表达式失败。
  • @B.Morris:你是对的。尽管如此,我认为如果不验证 catrm 命令的下落,问题就无法解决,正如 Benjamin 所指出的,PATH 变量的值也可能很有趣(结果env 命令)。
  • @Xero:在这种情况下,我建议您检查您的PATH 变量,看看如何将/usr/bin 目录添加到该变量。

标签: bash shell executable


【解决方案1】:

这并不能解决找不到命令的问题。

在创建文件之前测试文件是否存在会引入竞争条件。创建目录是一个原子操作。

declare -r LOCKDIR='program.run'
declare -r PIDFILE="$LOCKDIR/program.pid"

if ! mkdir "$LOCKDIR"; then
  # the lockdir already exists.
  # some unavoidable potential race conditions in here
  if [[ -f "$PIDFILE" ]]; then
    pid=$(< "$PIDFILE" )
    if kill -0 $pid 2>/dev/null; then
      echo "Another process is running with the last stored PID" >&2
      # no guarantee that it's actually this program
      # you can check it if you want (use pgrep, or "/proc/$pid/cmdline" if you're on linux)
      exit 1
    fi
    # if we get here, there's no process with that pid,
    # so it should be safe to carry on
  fi
fi

# write the pidfile
echo "$$" > "$PIDFILE"

即使程序意外退出,您也应该删除 lockdir:

cleanup() {
  rm "$LOCKDIR/$PIDFILE" &&
  rmdir "$LOCKDIR" ||
  echo "can't cleanup the lock directory" >&2
}
trap cleanup EXIT

【讨论】:

  • 感谢您提供的信息,它非常有帮助!我目前正在检查 PATH 以查看为什么它没有注册 cat, rm ...
猜你喜欢
  • 2020-01-22
  • 2015-01-31
  • 2015-06-15
  • 1970-01-01
  • 1970-01-01
  • 2013-12-09
  • 1970-01-01
  • 2021-01-26
  • 1970-01-01
相关资源
最近更新 更多