如何在Rust程序中将变量传入bash命令行参数?
Rust变量传入命令参数的解决方法
你当前代码里的"GPUTargetFanSpeed[fan:0]=speed_output"是将字符串字面量传递给命令,Rust不会自动识别并替换其中的变量名,所以变量speed_output的值没有生效。
解决方法很简单,用Rust的format!宏拼接出正确的参数字符串即可:
let speed_output = 70; Command::new("nvidia-settings") .arg("-a") .arg(format!("GPUTargetFanSpeed[fan:0]={}", speed_output)) .spawn() .expect("nvidia-settings command failed to execute");
format!宏会把speed_output的实际值插入到字符串的对应位置,生成类似"GPUTargetFanSpeed[fan:0]=70"的参数传递给nvidia-settings。
另外注意:不需要通过bash中转执行命令,直接用Command调用目标程序更安全,还能避免shell注入风险,同时也省去了变量转义的麻烦。
内容的提问来源于stack exchange,提问作者UnknownSuperficialNight
相关产品推荐
相关产品推荐

