gpt4 book ai didi

linux - 如何使用 shell 脚本中的选项和参数启动自定义二进制文件

转载 作者:太空宇宙 更新时间:2023-11-04 12:31:44 30 4
gpt4 key购买 nike

我不知道如何使用 shell 脚本的参数启动一个自己编写的程序。如果我所在的文件夹的父文件夹包含二进制文件,那么我可以使用

启动程序
$ ../binary --opt1 arg1 --opt2 arg2

现在,假设参数和选项列在当前文件夹的文件 args 中。

参数.txt:

--opt1 arg1 --opt2 arg2

如果我尝试从当前文件夹中的 shell 脚本执行二进制文件,例如:

$ ./script.sh args.txt

脚本.sh:

#!/bin/bash

if [ $# != 1 ]
then
exit 1;
fi

params=$(<"$1")

../binary "$params"
# ../binary <<<"$params" doesn't work either.

我怎样才能让它工作?

编辑(更新脚本):

#!/bin/bash

if [ $# != 1 ]
then
exit 1;
fi

params=$(<"$1")

START=$(date +%s)
../binary "$params"
# ../binary <<<"$params" doesn't work either.
END=$(date +%s)
DIFF=$(( $END - $START ))
echo "Test took $DIFF seconds"

最佳答案

使用命令替换:

$ ./script.sh args.txt

./script.sh 的内容

#!/bin/bash
../binary $(< "$1")

Command Substitution

Command substitution allows the output of a command to replace the command name. There are two forms:

          $(command)
or
`command`

Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting. The command substitution $(cat file) can be replaced by the equivalent but faster $(< file).

When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or \. The first back‐quote not preceded by a backslash terminates the command substitution. When using the $(command) form, all characters between the parentheses make up the command; none are treated specially.

Command substitutions may be nested. To nest when using the backquoted form, escape the inner backquotes with backslashes. If the substitution appears within double quotes, word splitting and pathname expansion are not performed on the results.

关于linux - 如何使用 shell 脚本中的选项和参数启动自定义二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43099224/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com