fish-shell/share/functions/psub.fish
2017-07-13 14:12:51 -07:00

62 lines
1.8 KiB
Fish

function psub --description "Read from stdin into a file and output the filename. Remove the file when the command that called psub exits."
set -l options 'h/help' 'f/file' 's/suffix='
argparse -n psub --max-args=0 $options -- $argv
or return
if set -q _flag_help
__fish_print_help psub
return 0
end
set -l dirname
set -l filename
set -l funcname
if not status --is-command-substitution
printf (_ "%s: Not inside of command substitution") psub >&2
return 1
end
set -l tmpdir /tmp
set -q TMPDIR
and set tmpdir $TMPDIR
if not set -q _flag_file
# Write output to pipe. This needs to be done in the background so
# that the command substitution exits without needing to wait for
# all the commands to exit
set dirname (mktemp -d $tmpdir/.psub.XXXXXXXXXX)
or return
set filename $dirname/psub.fifo"$_flag_suffix"
mkfifo $filename
cat >$filename &
else if test -z "$_flag_suffix"
set filename (mktemp $tmpdir/.psub.XXXXXXXXXX)
cat >$filename
else
set dirname (mktemp -d $tmpdir/.psub.XXXXXXXXXX)
set filename $dirname/psub"$_flag_suffix"
cat >$filename
end
# Write filename to stdout
echo $filename
# Find unique function name
while true
set funcname __fish_psub_(random)
if not functions $funcname >/dev/null ^/dev/null
break
end
end
# Make sure we erase file when caller exits
function $funcname --on-job-exit caller --inherit-variable filename --inherit-variable dirname --inherit-variable funcname
command rm $filename
if count $dirname >/dev/null
command rmdir $dirname
end
functions -e $funcname
end
end