在 || 后面放两个命令

Jos*_*uaD 5 bash

我想检查一下以确保有一些命令可用。如果不是,我想打印一条错误消息然后退出。

我想在不检查变量的情况下执行此操作,因为它是脚本中的一个小点,我不希望它散布在一堆行上。

我想使用的形状基本上是这样的:

rsync --help >> /dev/null 2>&1 || printf "%s\n" "rsync not found, exiting."; exit 1
Run Code Online (Sandbox Code Playgroud)

不幸的是,exit 1不管 rsync 结果如何,都会执行。

有没有办法在 bash 中使用这个 perl 类型的 die 消息,或者没有?

Jef*_*ler 13

为了直接回答问题,大括号将命令组合在一起,因此:

rsync --help >> /dev/null 2>&1 || { printf "%s\n" "rsync not found, exiting."; exit 1; }
Run Code Online (Sandbox Code Playgroud)

作为做你想做的事情的建议,但以另一种方式:

#!/usr/bin/env bash
for c in rsync ls doesnotexist othercommand grep
do
  if ! type "$c" &> /dev/null
  then 
    printf "$c not found, exiting\n"
    exit 1
  fi
done
Run Code Online (Sandbox Code Playgroud)

如果你想die在 shell 中模拟 perl :

function die {
  printf "%s\n" "$@" >&2
  exit 1
}

# ...
if ! type "$c" &> /dev/null
then
  die "$c not found, exiting"
fi
# ...
Run Code Online (Sandbox Code Playgroud)

  • 请注意,`cmd &> /dev/null` 在 POSIX shell 中的含义有所不同。那是在后台运行 `cmd`,然后执行无命令重定向到 /dev/null。还要注意 `die()` 标准语法,而不是 `function die` ksh 语法。 (2认同)

pfn*_*sel 5

一定要单线吗?我不是短路的忠实粉丝。我会这样写:

if ! rsync --help &>/dev/null; then
    printf "%s\n" "rsync not found, exiting."
    exit 1
fi
Run Code Online (Sandbox Code Playgroud)