bash - 如何在 bash 中打印用法和缺少参数错误?

标签 bash

我有一个需要 5 个参数的 bash 脚本。如果其中任何一个丢失并退出那里,我想打印用法和丢失的参数错误。还有帮助选项,它只打印 $usage。

#script.sh
usage="$0 param1 param2 param3 param4 param5
         param1 is ..
         param2 is ..
         param3 is ..
         param4 is ..
         param5 is .."

#if script.sh
# prints $usage and all param missing

#if script.sh param1 param2 param3
# print $usage and param4 and param5 missing and exit and so on

# script.sh -h
# just print $usage

最佳答案

你可以使用

var=${1:?error message}

它在 $var 中存储 $1 的值(如果已设置),如果未设置,则显示错误消息并停止执行.

例如:

src_dir="${1:?Missing source dir}"
dst_dir="${2:?Missing destination dir}"
src_file="${3:?Missing source file}"
dst_file="${4:?Missing destination file}"

# if execution reach this, nothing is missing

src_path="$src_dir/$src_file"
dst_path="$dst_dir/$dst_file"
echo "Moving $src_path to $dst_path"
mv "$src_path" "$dst_path"

关于bash - 如何在 bash 中打印用法和缺少参数错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33190120/

相关文章:

linux - 使用 awk 命令用逗号替换双引号 csv 文件中的管道

linux - 如果出现问题,如何让 ksh 脚本自行终止?

Bash Shell 使用 "for"循环列出文件

linux - 我从 .profile 和 .bashrc 中删除了路径,但仍然存在于 $PATH 中

linux - 如何创建指向目标目录中最新目录的符号链接(symbolic link)?

bash - SSH 到 wpengine 在 Windows 命令终端中有效,但在 git bash 中无效

bash - 通过索引访问 $*(或 $@)的元素

bash - 计算文件中 10 位数字的个数

file - 在包含 '>' 字符的行拆分文件

bash - 如何在 bash3.x 中获取子 shell 的 PID?