1

I have this command which works fine on Ubuntu but on macOS I get an error.

The command:

sudo $(grep -qxF '127.0.0.1        app.local' /etc/hosts || echo '127.0.0.1     app.local' >> /etc/hosts)

Output:

usage: sudo -h | -K | -k | -V
usage: sudo -v [-AknS] [-g group] [-h host] [-p prompt] [-u user]
usage: sudo -l [-AknS] [-g group] [-h host] [-p prompt] [-U user] [-u user] [command]
usage: sudo [-AbEHknPS] [-C num] [-g group] [-h host] [-p prompt] [-u user] [VAR=value] [-i|-s] [<command>]
usage: sudo -e [-AknS] [-C num] [-g group] [-h host] [-p prompt] [-u user] file ...
2
  • @dan The return code isn't relevant for sudo, the text on stdout is. Neither grep -q nor echo ... >> file produce any shell-executable text though.
    – nohillside
    Commented Jul 22, 2019 at 9:55
  • 1
    /etc/hosts works differently under Macos. Be careful. Commented Jul 22, 2019 at 10:06

1 Answer 1

3

The command as written doesn't really make sense, the command substitution will always return an empty string (and the part after the || will fail for non-root users). If you are looking for a way to add a line to /etc/hosts if there is no entry yet, try

grep -qxF '127.0.0.1        app.local' /etc/hosts ||
    sudo sh -c "echo '127.0.0.1        app.local' >> /etc/hosts"

PS: Relying on the number of spaces in the grep part is asking for trouble, maybe better use a regexp instead

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .