Search code examples
scriptingzshzshrcyoutube-dl

issue with a modification of youtube-dl in .zshrc


the code I have in my .zshrc is:

ytdcd () {  #youtube-dl that automatically puts stuff in a specific folder and returns to the former working directory after.
    cd ~/youtube/new/ && {
        youtube-dl "$@"
        cd - > /dev/null
    }
}
ytd() { #sofar, this function can only take one page. so, i can only send one youttube video code per line. will modify it to accept multiple lines..
    for i in $*;
        do
        params=" $params https://youtu.be/$i"
    done

    ytdcd -f 18 $params
}

so, on the commandline (terminal), when i enter ytd DFreHo3UCD0, i would like to have the video at https://youtu.be/DFreHo3UCD0 to be downloaded. the problem is that when I enter the command in succession, the system just tries to download the video for the previous command and rightly claims the download is complete.

For example, entering:

> ytd  DFreHo3UCD0
> ytd  L3my9luehfU

would not attempt to download the video for L3my9luehfU but only the video for DFreHo3UCD0 twice.


Solution

  • I would declare param as local, so that you are not appending url after urls...

    You can try to add this awesome function to your .zshrc:

    funfun() {
            local _fun1="$_fun1 fun1!"
            _fun2="$_fun2 fun2!"
    
            echo "1 says: $_fun1"
            echo "2 says: $_fun2"
    }
    

    To observe the thing ;)

    EDIT (Explanation):

    When sourcing shell script, you add it to you current environment, that is why you can run those function you define. So, when those function use variables, by default, those variable will be global and accessible from anywhere in your environment! Therefore, In this case param is defined globally for all the length of your shell session. Since you want to allow the download of several video at once, you are appending values to this global variable, which will grow all the time.

    Enforcing local tells zsh to limit the scope of params to the function only.

    Another solution is to reset the variable when you call the function.