bash - 将变量从 bash 传递到可执行文件(使用 stdin 读取参数)

标签 bash variables executable stdin

我有以下test.cpp C++ 程序

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

int main()
{
    float a,b,c;
    cout<<"Give 1st number";
    cin>>a;
    cout<<"Give 2nd number:";
    cin>>b;

    c=a+b;
    cout<<"\n"<<a<<"+"<<b<<"="<<c<<endl;

return 0;
}

我想创建一个shell脚本来提供输入变量。 我知道如何传递一个变量,并且我想知道是否有一种方法可以传递 2 个变量... 就像下面的 test.sh 文件不起作用

#!/bin/bash

g++ test.cpp -o testexe
chmod +x testexe

a=1
b=2

./testexe <<< $a $b

最佳答案

不仅兼容 bash,还兼容 /bin/sh -- 同时避免管道开销 -- 使用定界符:

./testexe <<EOF
$a
$b
EOF

如果您不关心管道开销(并且仍然保持 /bin/sh 兼容性,任何使用 <<< 的答案都缺乏兼容性):

printf '%s\n' "$a" "$b" |  ./testexe

如果你不关心/bin/sh兼容性:

./testexe <<<"$a"$'\n'"$b"

关于bash - 将变量从 bash 传递到可执行文件(使用 stdin 读取参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29947782/

相关文章:

bash - jq : command not found in GitLab CI file

variables - Powershell 变量路径中的通配符

c - 将 go linker 构建为独立工具

php - 在 PHP 页面之间传递变量

Javascript 从单个下拉列表填充 2 个文本框

audio - 如何编写脚本来使用应用程序

Python 脚本在 IDLE Shell 和 Bash 中作为 .py 而不是 .exe 运行

git - 当依赖项位于私有(private)存储库中时如何使用 Composer 通过 AWS Codeploy 进行部署

bash - 如何按两列的比例对 CSV 文件的列进行排序?

linux - 在 bash 中打印字符串模式和新行之间的文本