Last Updated: February 25, 2016
·
431
· mkaito

Piping to shell functions

Once upon a time, I found the need to know whether a function was being piped to when called. This function can either parse torrent IDs from the output of transmission-remote -l via pipe, or accept a list of torrent IDs. This way, I can pipe the torrent list to grep for quick filtering, and then pipe to my helper functions to operate on the filtered torrents.

function ttm {
 local torrents
 local target

 if [[ ! -t 0 ]]; then
 # We're being fed on stdin
 torrents=()

 while read line; do
 torrents+=( $(echo $line | awk '{print $1}') )
 done

 torrents=${(j:,:)torrents}
 target=$(realpath "$1")
 echo "Moving torrents: ${torrents} -> ${target}."
 elif [[ ! -z "$1" ]]; then
 torrents="$1"
 target=$(realpath "$2")
 fi

 [[ -z "$torrents" ]] && echo "Won't move all torrents!" && return 2
 [[ -z "$target" ]] && echo "Please specify a target folder" && return 2

 tt "-t${torrents}" --move "${target}"
}