fish

Why does the or operator in fish seem to not work


function shapeshift
   argparse 'h/help' -- $argv
   if not set -q argv[1] $argv or if set -q _flag_help 
      echo "Shapeshift lets you change into another root system."
      echo "It is a simple tool that mounts, and chroots a partition of your choice."
      echo ""
      echo "Use it in the following way:"
      set_color green; echo "shapeshift nvme0n1p4"; set_color normal
      echo ""
      echo "Here is a list of the available partitions:"
      echo ""
      sudo lsblk -o NAME,SIZE,MOUNTPOINTS,TYPE | awk '$4 == "part"'
   end
end

I cant seem to get both, calling with an argument and calling with --help, seem to get working at the same time.

I tried several different versions of this code, and always seems to break the code, once I chain both events together by an or. No matter which one I call first, or if I use a separate if statement in front of the second command or not. It always seems to fail.


Solution

  • In fish shell, "or" is specially recognized when used as a command, but only in "command position;" otherwise it's just a plain old string.

    The second issue is that one should not write if X; or if Y because this tests the result of a nested if statement. Instead, write if X; or Y

    For example, don't do this:

    if not set -q argv[1] or if set -q _flag_help
    

    This is a single invocation of set which passes "or", "if", etc as arguments, which is not intended. Instead, make a new command with a semicolon, and no nested "if":

    if not set -q argv[1]; or set -q _flag_help
    

    Or use a newline:

    if not set -q argv[1]
    or set -q _flag_help
    ...
    end
    

    Alternatively you may prefer the || syntax, which itself creates a new command:

    if not set -q argv[1] || set -q _flag_help
    ...
    

    Note set -q argv[1] is sufficient to test that there is at least one argument. Do not also pass $argv; that would check if any of the arguments is the name of a variable.

    So give this a try:

    function shapeshift
       argparse 'h/help' -- $argv
       if not set -q argv[1] || set -q _flag_help 
          echo "Shapeshift lets you change into another root system."
          echo "It is a simple tool that mounts, and chroots a partition of your choice."
          echo ""
          echo "Use it in the following way:"
          set_color green; echo "shapeshift nvme0n1p4"; set_color normal
          echo ""
          echo "Here is a list of the available partitions:"
          echo ""
          sudo lsblk -o NAME,SIZE,MOUNTPOINTS,TYPE | awk '$4 == "part"'
       end
    end