Last Updated: February 25, 2016
· 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

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

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

    [[ -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}"