简体   繁体   中英

Fish Shell function that works with piped input or with argument based input

I'm trying to create a fish shell function that will trim new lines from the input and then copy the input to the clipboard.

How can I write this function so that it will;

  • Process pipeline input (this works now)
  • Process first argument as if it were input piped to the function
  • Exit immediately in the case that no value is provided via argument or pipeline, right now tr will not exit without some value being passed in the pipeline

Code:

function copy --description 'Trim new lines and copy to clipboard'
    tr -d '\n' | pbcopy
end

Update that handles newlines better:

function copy --description 'Trim new lines and copy to clipboard'
  cat $argv ^/dev/null | while read -l line
    set argv $argv $line
  end

  test -z "$argv"; and return

  for i in $argv
    echo -n $i
  end | tr -d '\n' | pbcopy
end

This one was quite a challenge, but with a little bit of trickery it was possible. This function works as you described plus one caveat, if you write copy without any args then it will wait for your input indefinitely.

If you don't care for multiline copying you could remove the | tr -d '\\n' | tr -d '\\n' before read and then copy would also work. Because read is terminated by newline. So then it would automatically just accept up to the first newline, for example copy\\nme would copy just copy .

Code:

function copy --description 'Trim new lines and copy to clipboard'
  cat $argv ^/dev/null | tr -d '\n' | read -l input

  set -ql input; or set -l input $argv

  if test -n "$input"
    echo $input | tr -d '\n' | pbcopy
  end
end

Example:

➤ echo copy\nme | copy
Clipboard: copyme

➤ copy copy\nyou
Clipboard: copyyou

➤ echo | copy
Clipboard: copyyou

➤ copy
(Waiting for command indefinitely...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM