Setting commands with logic as "command"

How can I write commands like the following?

apps:
  myrootapp:
    command: "[[ $EUID -ne 0 ]] && echo 'This command needs root' || bin/myapp"

I currently get the following error:

Failed to generate snap metadata: The specified command "[[ $EUID -ne 0 ]] && echo 'This command needs root' || bin/myapp" defined in the app 'myrootapp' does not match the pattern expected by snapd.
The command must consist only of alphanumeric characters, spaces, and the following special characters: / . _ # : $ -

If not possible, what other approach do you suggest? If possible, I would like to avoid creating a separate script for such simple logic :blush:

i fear you have to … :frowning:

1 Like

I think having some simple logic in the command could really help to keep things tidy :blush:

BTW, is there any convention on where to put such scripts?

I was thinking of putting them under snap/wrappers and editing the yaml like

parts:
  mypart:
    plugin: go
    source: .
    source-type: git
    organize:
      snap/wrappers: bin/wrappers

apps:
  myrootapp:
    command: bin/wrapper/check_root_and_run.sh

Does it sound the right approach? :blush:

I think snapcraft will tell you off for using snap/wrappers, saying to use snap/local instead.

If the code you’re building is separate to your snap repository I personally just make a root level wrappers/extras/etc folder and use the dump plugin. If the code you’re building is next to the snapcraft.yaml, maybe snap/local makes the most sense.

But I don’t think there’s any convention other than not snap/arbitrary_folder_name

1 Like

Thanks, I’ll try your suggestion :blush:

Ok, in case it may be useful to somebody in the future, my final solution is the following:

[Project structure]
other_project_stuff
snap/
 - snapcraft.yaml
 - local/check_root
 - hooks

And check_root (remember to make it executable) is like this:

#!/bin/env bash

# Checks root
if [[ $EUID -ne 0 ]]
then
  echo 'This command needs root'
else
  "$@"
fi

Then I use it in snapcraft.yaml like this:

parts:
  mypart:
    plugin: go  # or whatever plugin you use
    source: .
    source-type: git
  
  wrappers:
    plugin: dump
    source: snap/local
    plugin: dump
    organize:
      "check_root": bin/check_root
    
apps:
  myapp:
    command: bin/check_root $SNAP/bin/myapp
1 Like