Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use pipeline in System.cmd?

Tags:

cmd

elixir

I have a function, which gets information of all usb connected devices.

connected_devices = :os.cmd('usb-devices | grep -A 1 Product=')

When I use :os.cmd, it works fine. However, since :os.cmd does not return error code, I would like to use System.cmd for better error handling.

connected_deivces = System.cmd("usb-devices", ["|", "grep", "-A", "1", "Product="])

So I tried to change function like above, but it does not execute command after pipeline.

How can I execute command with pipeline with System.cmd?

like image 485
D.R Avatar asked Dec 08 '25 06:12

D.R


1 Answers

System.cmd can only invoke one program directly. os:cmd passes the command to the default shell of the operating system which allows you to use pipes. To do the same thing with System.cmd, you can call /bin/sh if you're on a Unix:

System.cmd("/bin/sh", ["-c", "usb-devices | grep -A 1 Product="])
like image 194
Dogbert Avatar answered Dec 10 '25 00:12

Dogbert