macOS High Sierra, 10.13.3 (17D102)
- If I run in terminal
sysctl -n hw.memsize
it works fine, I get a number - If i run
which sysctl
i get/usr/sbin/sysctl
which seems correct
How to run the same command from shell script? Looking for cross-OS solution. Using pure sh everywhere.
I have tried:
#!/bin/sh
$("sysctl -n hw.memsize")
exit 1
1 Result: line 2: sysctl -n hw.memsize: command not found
#!/bin/sh
$("/usr/sbin/sysctl -n hw.memsize")
exit 1
2 Result: line 2: /usr/sbin/sysctl -n hw.memsize: No such file or directory
#!/bin/sh
echo `sysctl -n hw.memsize`
exit 1
3 Result: line 2: 17179869184: command not found
Not sure why command not found afte the correct output.
#!/bin/sh
eval "sysctl -n hw.memsize"
exit 1
4 Result: same as running in terminal: 17179869184 But i want to avoid eval.
While 4th works as epxected, it uses eval and i try to avoid it. 3rd seems almost correct and not sure why 2nd says no such file while it does exist.
sh script file has a+x chmod.
$(...)
. It's treating the entire quoted string as the name of the command to run, because, well, that's what quotes mean to do. Here you don't even need the$(...)
though, that's if you want to run a command in a subshell and get its stdout back as a string