如何将默认值传递给标志

发布于 2025-02-12 10:34:41 字数 594 浏览 0 评论 0原文

我需要将默认值传递到-c -t -u标志。 在-ci中需要无限 在-ti中需要1秒 在-u中,defauls是

#!/bin/bash

set -u

print_usage(){
echo "usage: script[-c] [-t] [-u] exe-name"
}
if [[ $# -eq 0 ]]; then
print_usage
exit 1
fi

while getopts :c:t:u: flag; do
case $flag in
c) counts=$OPTARG;;
t) timeout=$OPTARG;;
u) user_name=$OPTARG;;
esac
done

if [ $counts==true ]
    then
top -n ${counts}
    fi
if [ $timeout==true ]
    then
top -d ${timeout}
    fi
if [ $user_name==true ]
    then
top -u ${user_name}
    fi

我试图将类似的用户放在杰出的情况下,但它不起作用:

counts=
timeout=1
user_name=.

I need to pass defaults to the -c -t -u flags.
in the -c i need that to be infinite
in the -t i need that to be 1 sec
and in the -u the defauls is ANY user

#!/bin/bash

set -u

print_usage(){
echo "usage: script[-c] [-t] [-u] exe-name"
}
if [[ $# -eq 0 ]]; then
print_usage
exit 1
fi

while getopts :c:t:u: flag; do
case $flag in
c) counts=$OPTARG;;
t) timeout=$OPTARG;;
u) user_name=$OPTARG;;
esac
done

if [ $counts==true ]
    then
top -n ${counts}
    fi
if [ $timeout==true ]
    then
top -d ${timeout}
    fi
if [ $user_name==true ]
    then
top -u ${user_name}
    fi

I tried to put something like that in the biginning but it doesn't work:

counts=
timeout=1
user_name=.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暗藏城府 2025-02-19 10:34:41

在循环之前,将默认值分配给变量。

将数组用于可以容纳多个参数的变量。请参阅出于原因,请使用bash 设置一个参数。

然后,您可以执行具有所有参数合并的单个top命令。

#!/bin/bash

set -u

print_usage(){
    echo "usage: script [-c repetitions] [-t timeout] [-u username] exe-name"
}
if [[ $# -eq 0 ]]; then
    print_usage
    exit 1
fi

counts=()
timeout=(-d 1)
user_name=()

while getopts :c:t:u: flag; do
    case $flag in
        c) counts=(-n "$OPTARG");;
        t) timeout=(-d "$OPTARG");;
        u) user_name=(-u "$OPTARG");;
    esac
done

top "${counts[@]}" "${timeout[@]}" "${user_name[@]}"

Assign default values to the variables before the while loop.

Use arrays for variables that can hold multiple arguments. See Setting an argument with bash for the reasons.

You can then execute a single top command that has all the arguments combined.

#!/bin/bash

set -u

print_usage(){
    echo "usage: script [-c repetitions] [-t timeout] [-u username] exe-name"
}
if [[ $# -eq 0 ]]; then
    print_usage
    exit 1
fi

counts=()
timeout=(-d 1)
user_name=()

while getopts :c:t:u: flag; do
    case $flag in
        c) counts=(-n "$OPTARG");;
        t) timeout=(-d "$OPTARG");;
        u) user_name=(-u "$OPTARG");;
    esac
done

top "${counts[@]}" "${timeout[@]}" "${user_name[@]}"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文