如何读取 bash 中的变量并将这些变量作为参数传递给 C++ 程序

如何读取 bash 中的变量并将这些变量作为参数传递给 C++ 程序

我正在尝试读取 bash 脚本中的一些变量并将它们传递给 C++ 程序,该程序将接受这些变量作为参数。有什么帮助吗?我已经走到这一步了..但它不起作用......

echo -n 'Enter a name: '
read name
echo -n 'Enter a lastname: '
read lastname
./myprogram "$@"

答案1

第一个解决方案:
在脚本文件中写入以下行myscript.sh,然后执行不带任何参数的脚本,例如./myscript.sh.

#!/bin/bash

read -p "Enter your name: " name
read -p "Enter your lastname: lastname
./myprogram "${name}" "${lastname}"

笔记:在上面的脚本中,您提示输入姓名和姓氏,并将其存储在变量中,然后传递给您的 C++ 程序。

第二种解决方案:
在脚本中写入以下几行并将参数传递给脚本,例如./myscript.sh foo bar

#!/bin/bash   

./myprogram "$@"

笔记:在上面的脚本中,您将参数传递给 shell 脚本,它直接将所有参数传递给 C++ 程序。

相关内容