How to access remaining arguments in a fish script

帅比萌擦擦* 提交于 2019-12-20 09:29:50

问题


my-fish-script a b c d

Say you want to get the all arguments from the second argument onwards, so b c d.

In bash you can use shift to dump the first argument and access the remaining ones with "$@".

How would you solve the problem using the fish shell?


回答1:


In fish, your arguments are contained in the $argv list. Use list slicing to access a range of elements, e.g. $argv[2..-1] returns all arguments from the second to the last.

For example

function loop --description "loop <count> <command>"
  for i in (seq 1 $argv[1])
    eval $argv[2..-1]
  end
end

Usage

$ loop 3 echo hello world
hello world
hello world
hello world



回答2:


The behaviour of the shift command can be simulated with set -e/--erase VARIABLE_NAME.

The idea is to erase the first argument, then get the remaining arguments from the $argv list.

For example

function loop  --description "loop <count> <command>"
  set count $argv[1]
  set --erase argv[1]
  for i in (seq 1 $count)
    eval $argv
  end
end

Usage

$ loop 3 echo hello world
hello world
hello world
hello world



回答3:


You could also use read which is more readable in my opinion:

function loop
  echo $argv | read -l count command
  for i in (seq 1 $count)
    eval $command
  end
end

This works better especially when you want to use more than the first argument.

echo $argv | read -l first second rest


来源:https://stackoverflow.com/questions/24093649/how-to-access-remaining-arguments-in-a-fish-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!