C# - Send Command to Linux Using Variables

When I send a command to Linux with values hardcoded like:
response = SystemHelper.CommandExec("i2ctransfer", "-f -y -v 16 w2@0x18 0x30 0x12 r2");
I get a response on the terminal as
msg 0: addr 0x18, write, len 2, buf 0x30 0x12
msg 1: addr 0x18, read, len 2, buf 0x00 0x10
However if I replace the values with variables like so:
response = SystemHelper.CommandExec("i2ctransfer", $"-f -y -v 16 w2@0x18 {regPartA} {regPartB} r2");
I only get back msg 0 as response.
How can I pass in variables and get back the same response? Ideally I would get back the same response as I would when entering the command directly on the command line which is something like "0x10 0x00" but I can pull that out of the full response if it includes msg 1.
Answer
I've run into this exact issue before with i2ctransfer commands. The problem is usually how the shell interprets the arguments when they're passed through variables.
The issue is that when you use variables in your command, the shell doesn't parse them the same way as hardcoded values. Here's what's likely happening:
Your hardcoded version works because the arguments are properly separated:
"i2ctransfer", "-f -y -v 16 w2@0x18 0x30 0x12"
But with variables, it might be treating everything after the variable as one argument instead of separate hex values.
Try this fix:
string regPartA = "0x30 0x12";
string fullCommand = $"i2ctransfer -f -y -v 16 w2@0x18 {regPartA}";
response = SystemHelper.CommandExec("/bin/bash", $"-c \"{fullCommand}\"");
If that doesn't work, try building it this way:
string regPartA = "0x30 0x12";
response = SystemHelper.CommandExec("/bin/bash", $"-c \"i2ctransfer -f -y -v 16 w2@0x18 {regPartA}\"");
The key is using /bin/bash -c
to ensure the shell properly interprets your command with variables. I2C commands can be finicky about argument parsing.
Also, double-check that your regPartA
variable contains exactly "0x30 0x12"
(with the space) - any extra characters or formatting differences will cause issues.
Enjoyed this question?
Check out more content on our blog or follow us on social media.
Browse more questions