A while ago I made a tiny function in my ~/.zshrc to download a video from the link in my clipboard. I use this nearly every day to share videos with people without forcing them to watch it on whatever site I found it. What’s a script/alias that you use a lot?

# Download clipboard to tmp with yt-dlp
tmpv() {
  cd /tmp/ && yt-dlp "$(wl-paste)"
}
  • jsomae@lemmy.ml
    link
    fedilink
    arrow-up
    21
    arrow-down
    1
    ·
    2 months ago

    I wrote a script called please. You input please followed by any other command (e.g. please git clone, please wget blahblah) and a robotic voice will say “affirmative,” then the command will run, and when it completes, the robotic voice reads out the exit code (e.g. “completed successfully” or “failed with status 1” etc.)

    This is useful for when you have a command that takes a long time and you want to be alerted when it’s finished. And it’s a gentleman.

      • jsomae@lemmy.ml
        link
        fedilink
        arrow-up
        17
        ·
        2 months ago

        It’s full of random shit I put in as a joke, but here it is. You can use please -s to get lightly roasted when your command fails.

        spoiler
        #!/bin/bash
        # announces success or failure of task
        
        if ! command -v "spd-say" > /dev/null
        then
            echo "spd-say must be installed."
            exit -1
        fi
        
        VOLUME=0
        SERIOUS=1
        FINISH_ONLY=0
        
        if [ $# -ge 2 ]
        then
            if [ $1 == "-i" ]
            then
                # parse volume from command line
                VOLUME=$2
                shift 2
            fi
        fi
        
        spd-say -C
        
        # force stop speech synthesizer
        killall -q speech-dispatcher
        
        # androgynous voice
        # __sayfn="spd-say -i -80 -t female3"
        
        # deep voice
        __sayfn="spd-say -i $VOLUME -r -10 -p -100 -t male3"
        
        function _sayfn {
            $__sayfn "$@" 2>/dev/null
            if [ $? -ne 0 ]
            then
                $__sayfn "$@"
            fi
        }
        
        if [ $# -eq 0 ] || [ "$1" == "--help" ]
        then
            _sayfn "Directive required."
            echo "Usage: please [-i volume] [-s|--serious] [-f|--finish] <command...>"
            echo "       please [-i volume] --say text"
            echo "       -i: volume in range -100 to +100"
            echo "       --serious, -s: no silliness. Serious only. (Just kidding.)"
            echo "       --finish, -f: do not announce start"
            exit -2
        fi
        
        # threading issue
        sleep 0.001
        
        if [ $# -ge 2 ]
        then
            if [ $1 == "--say" ]
            then
                # _sayfn the given line
                shift 1
                _sayfn "$@"
                exit 0
            fi
        
            if [ $1 == "--serious" ] || [ $1 == "-s" ]
            then
                shift 1
                SERIOUS=0
            fi
            
            if [ $1 == "--finish" ] || [ $1 == "-f" ]
            then
                shift 1
                FINISH_ONLY=1
            fi
        fi
        
        i=$(shuf -n1 -e "." "!") # inflection on voice
        
        if [ "$FINISH_ONLY" -eq 0 ]
        then
            if [ "$SERIOUS" -eq 0 ]
            then
                # startup lines (randomized for character)
                _sayfn -r -5 -x ".<break time=\"60ms\"/>$(shuf -n1 -e \
                    'Proceeding As Directed...' \
                    'By your command...' \
                    'By your command...' \
                    'By the power ov greyskaall!' \
                    'By your command,line...' \
                    'As you wish...' \
                    'Stand by.' \
                    'Engaged...' \
                    'Initializing...' \
                    'Activating' \
                    'At once!' \
                    "Post Haste$i" \
                    'it shall be done immediately' \
                    'Very well.' \
                    'It shall be so.' \
                    "righty-o$i" \
                    "Affirmative$i" \
                    "Acknowledged$i" \
                    "Confirmed$i" \
                )"
            else
                _sayfn -r -5 -x ".<break time=\"60ms\"/>Engaged..."
            fi
        
            if [ $? -ne 0 ]
            then
                _sayfn "Speech engine failure."
                echo "Failed to run speech engine. Cancelling task."
                exit -3
            fi
        fi
        
        if ! command -v "$1" > /dev/null
        then
            # _sayfn a little faster because this exits fast.
            _sayfn -r +10 "Unable to comply? invalid command."
            >&2 echo "$1: command not found."
            exit -4
        fi
        
        eval " $@"
        result=$?
        i=$(shuf -n1 -e "," "!" "?") # inflection on voice
        transition=$(shuf -n1 -e "; error" ", with error" "; status")
        taskname=$(shuf -n1 -e "task" "task" "command" "objective" "mission" "procedure" "routine")
        errtext=$(shuf -n1 -e "Task_failed" "Task_failed" "Task_resulted_in_failure" "Procedure_terminated_in_an_error" "An_error_has_occurred" "Auxilliary_system_failure" "system_failure")
        consolation=$(shuf -n1 -e "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "Attention required." "Attention is required!" "Perhaps It was inevitable." "It may or may not be cause for alarm." "Perhaps Machines too, are fallible." "Apologies" "Hopefully nobody else was watching" "shazbot" "maybe next time." "Nobody could have predicted this outcome." "I'm very sorry." "how unfortunate." "remember: don't panic" "oh dear" "Nothing could have been done to prevent this" "Remember: No disasters are fully preventable" "perhaps the only winning move is not to play" "Remember: Failure is our teacher, not our undertaker." "Remember: If at first you don't succeed... try again." "Remember: If at first you don't succeed... try... try again." "But your friends still love you." "Remember: the machine is not your enemy." "Command?" "Awaiting further instructions." "Remember: Logic is the beginning of wisdom... not the end of it." "Remember: When you eliminate the impossible, whatever remains, however improbable, must be the truth." "Keep at it. Victory is within reach." "Remember: The road to success and the road to failure are almost exactly the same." "Now, while this could have gone better, it could also have gone much worse." "Remember: we do this not because it is easy, but because we thought it was going to be easy." "Don't give up." "It has now been... -- zero... -- days, since the last serious failure." "Remember: instead of documenting the problem, you can fix it." "Remember: Artificial intelligence is no match for artificial stupidity." "Standing by," "Remember: with every failure, we get closer to success." "We live in a society." "sometimes failure is not an option; it's a necessity." "Keep at it." "Remember: mistakes are just the first step on the road to failure... <break time=\"250ms\"/> I mean success." "Don't leave. The drones need you... <break time=\"350ms\"/> They look up to you." "Try again, for great justice." "fantastic" "brilliant" "did you really think that would work?")
        
        if [ $SERIOUS -eq 0 ]
        then
            # perhaps some silliness.
            if [ $result -eq 0 ]
            then
                _sayfn --wait "$(shuf -n1 -e \
                   "$taskname complete. All systems nominal" \
                   "$taskname completed successfully." \
                   "$taskname resulted in success." \
                   "$taskname yielded a successful result." \
                   "$taskname concluded successfully." \
                   "$taskname completed as instructed." \
                   "Jobs done." \
                )" &
            else
                if [ $result -eq 1 ]
                then
                    _sayfn -x --wait "$(shuf -n1 -e \
                       "Alert$i Primary system failure. Attention is required." \
                       "Alert$i System failure$i Attention required! $consolation" \
                       "Alert$i $taskname resulted in failure! <break time=\"150ms\"/> $consolation" \
                       "Alert$i $taskname was not completed as intended; $consolation" \
                       "Alert$i An error has occurred! <break time=\"220ms\"/> $consolation" \
                    )" &
                   
                else
                    _sayfn --wait -x "Alert$i $errtext$transition code $result! <break time=\"350ms\"/> $consolation" &
                fi
            fi
        else
            # no silliness here.
            if [ $result -eq 0 ]
            then
                _sayfn --wait "Command complete."
            else
                if [ $result -eq 1 ]
                then
                    _sayfn -x --wait "Alert. Command failed; error code $result!"
                fi
            fi
        fi
        
        exit $result
        
    • Azzk1kr@feddit.nl
      link
      fedilink
      English
      arrow-up
      1
      ·
      2 months ago

      You can also use something like notifyd to generate a pop up for visual feedback :) I can’t remember the exact command right now though. Differs per distro or desktop environment, obviously.

    • data1701d (He/Him)@startrek.website
      link
      fedilink
      English
      arrow-up
      1
      ·
      2 months ago

      I once experimented with something similar, except it was supported to trigger my smart speaker and drop into another part of the house to tell me.

      Honestly, I really need to replace my proprietary smart speaker system with something self-hosted; it’s just I only recently have had the time to start cinsidering.

  • kibiz0r@midwest.social
    link
    fedilink
    English
    arrow-up
    14
    ·
    edit-2
    2 months ago

    I often want to know the status code of a curl request, but I don’t want that extra information to mess with the response body that it prints to stdout.

    What to do?

    Render an image instead, of course!

    curlcat takes the same params as curl, but it uses iTerm2’s imgcat tool to draw an “HTTP Cat” of the status code.

    It even sends the image to stderr instead of stdout, so you can still pipe curlcat to jq or something.

    #!/usr/bin/env zsh
    
    stdoutfile=$( mktemp )
    curl -sw "\n%{http_code}" $@ > $stdoutfile
    exitcode=$?
    
    if [[ $exitcode == 0 ]]; then
      statuscode=$( cat $stdoutfile | tail -1 )
    
      if [[ ! -f $HOME/.httpcat$statuscode ]]; then
        curl -so $HOME/.httpcat$statuscode https://http.cat/$statuscode
      fi
    
      imgcat $HOME/.httpcat$statuscode 1>&2
    fi
    
    cat $stdoutfile | ghead -n -1
    
    exit $exitcode
    

    Note: This is macOS-specific, as written, but as long as your terminal supports images, you should be able to adapt it just fine.

    • Revan343@lemmy.ca
      link
      fedilink
      arrow-up
      1
      ·
      2 months ago

      alias sl='ls | while IFS= read -r line; do while IFS= read -r -n1 char; do if [[ -z "$char" ]]; then printf "\n"; else printf "%s" "$char"; sleep 0.05; fi; done <<< "$line"; done'

      I can’t easily check if it works until I get home to my laptop, but you get the idea

  • golden_zealot@lemmy.ml
    link
    fedilink
    English
    arrow-up
    6
    ·
    2 months ago

    alias clip='xclip -selection clipboard'

    When you pipe to this, for example ls | clip, it will stick the output of the command ran into the clipboard without needing to manually copy the output.

    • mmmm@sopuli.xyz
      link
      fedilink
      arrow-up
      3
      ·
      edit-2
      2 months ago

      I use a KDE variant of this that uses klipper instead (whatever you pipe to this will be available in klipper):

      ` #!/bin/sh

      function copy {
          if ! tty -s && stdin=$(</dev/stdin) && [[ "$stdin" ]]; then
              stdin=$stdin$(cat)
              qdbus6 org.kde.klipper /klipper setClipboardContents "$stdin"
              exit
          fi
      
          qdbus6 org.kde.klipper /klipper getClipboardContents
      }
      
      copy $@`
      
  • djblw@lemmy.world
    link
    fedilink
    arrow-up
    6
    ·
    2 months ago

    This tmux wrapper is remarkably convenient:

    Usage:

    # Usage: t [session-name]
    #
    # With no arguments:
    #   Lists existing tmux sessions, or prints "[No sessions]" if none exist.
    #
    # With a session name:
    #   Attempts to attach to the named tmux session.
    #   If the session does not exist, creates a new session with that name.
    #
    # Examples:
    #   t            # Lists all tmux sessions
    #   t dev        # Attaches to "dev" session or creates it if it doesn't exist
    
    function t {
    	if [[ -z $1 ]]; then
    		tmux ls 2> /dev/null || echo "[No sessions]"
    	else
    		tmux attach -t $@ 2> /dev/null
    		if [[ $? -ne 0 ]]; then
    			tmux new -s $@
    		fi
    	fi
    }
    
  • gonzo-rand19@moist.catsweat.com
    link
    fedilink
    arrow-up
    6
    ·
    2 months ago

    Here are probably the most useful ones. I prefer for rm to be interactive so I don’t accidentally delete something important and for mkdir to create a parent directory if necessary.

    alias rm='rm -i'
    alias mkdir='mkdir -p'
    alias podup='podman-compose down && podman-compose pull && podman-compose up -d'
    

    This extract function (which I didn’t make myself, I got it from when I was using nakeDeb) has been pretty useful too.

    function extract()
    {
         if [ -f $1 ] ; then
             case $1 in
                 *.tar.bz2)   tar xvjf $1     ;;
                 *.tar.gz)    tar xvzf $1     ;;
                 *.bz2)       bunzip2 $1      ;;
                 *.rar)       unrar x $1      ;;
                 *.gz)        gunzip $1       ;;
                 *.tar)       tar xvf $1      ;;
                 *.tbz2)      tar xvjf $1     ;;
                 *.tgz)       tar xvzf $1     ;;
                 *.zip)       unzip $1        ;;
                 *.Z)         uncompress $1   ;;
                 *.7z)        7z x $1         ;;
                 *.xz)        unxz $1         ;;
                 *)           echo "'$1' cannot be extracted via >extract<" ;;
             esac
         else
             echo "'$1' is not a valid file"
         fi
    }
    
    • frozen@lemmy.frozeninferno.xyz
      link
      fedilink
      arrow-up
      2
      ·
      2 months ago

      I have a similar docker/podman alias, except I pull first. This greatly reduces downtime between down and up, which is nice for critical services.

  • Bo7a@lemmy.ca
    link
    fedilink
    arrow-up
    5
    ·
    2 months ago
    #Create a dir and cd into it
    mkcd() { mkdir -p "$@" && cd "$@"; }
    
    • iliketurtiles@programming.dev
      link
      fedilink
      English
      arrow-up
      2
      ·
      edit-2
      2 months ago

      Here’s a script I use a lot that creates a temporary directory, cds you into it, then cleans up after you exit. Ctrl-D to exit, and it takes you back to the directory you were in before.

      Similar to what another user shared replying to this comment but mine is in bash + does these extra stuff.

      #!/bin/bash
      
      function make_temp_dir {
          # create a temporary directory and cd into it.
          TMP_CURR="$PWD";
          TMP_TMPDIR="$(mktemp -d)";
          cd "$TMP_TMPDIR";
      }
      
      function del_temp_dir {
          # delete the temporary directory once done using it.
          cd "$TMP_CURR";
          rm -r "$TMP_TMPDIR";
      }
      
      function temp {
          # create an empty temp directory and cd into it. Ctr-D to exit, which will
          # delete the temp directory
          make_temp_dir;
          bash -i;
          del_temp_dir;
      }
      
      temp
      
  • SuperiorOne@lemmy.ml
    link
    fedilink
    English
    arrow-up
    4
    ·
    2 months ago

    jmpd(jump directory): fuzzy finds and opens directory with fzf

    # fish shell
    function jmpd
        set _selection $(fzf --walker=dir);
        if test -n "$_selection"
            cd "$_selection";
        end
    end
    
  • arcayne@lemmy.today
    link
    fedilink
    English
    arrow-up
    4
    ·
    2 months ago

    Well, my full functions.sh won’t fit in a comment, so here’s 2 of my more unique functions that makes life a little easier when contributing to busy OSS projects:

    # Git fork sync functions
    # Assumes standard convention: origin = your fork, upstream = original repo
    ## Sync fork with upstream before starting work
    gss() {
            # Safety checks
            if ! git rev-parse --git-dir >/dev/null 2>&1; then
                    echo "❌ Not in a git repository"
                    return 1
            fi
    
            # Check if we're in a git operation state
            local git_dir=$(git rev-parse --git-dir)
            if [[ -f "$git_dir/rebase-merge/interactive" ]] || [[ -d "$git_dir/rebase-apply" ]] || [[ -f "$git_dir/MERGE_HEAD" ]]; then
                    echo "❌ Git operation in progress. Complete or abort current rebase/merge first:"
                    echo "   git rebase --continue  (after resolving conflicts)"
                    echo "   git rebase --abort     (to cancel rebase)"
                    echo "   git merge --abort      (to cancel merge)"
                    return 1
            fi
    
            # Check for uncommitted changes
            if ! git diff-index --quiet HEAD -- 2>/dev/null; then
                    echo "❌ You have uncommitted changes. Commit or stash them first:"
                    git status --porcelain
                    echo ""
                    echo "💡 Quick fix: git add . && git commit -m 'WIP' or git stash"
                    return 1
            fi
    
            # Check for required remotes
            if ! git remote get-url upstream >/dev/null 2>&1; then
                    echo "❌ No 'upstream' remote found. Add it first:"
                    echo "   git remote add upstream <upstream-repo-url>"
                    return 1
            fi
    
            if ! git remote get-url origin >/dev/null 2>&1; then
                    echo "❌ No 'origin' remote found. Add it first:"
                    echo "   git remote add origin <your-fork-url>"
                    return 1
            fi
    
            local current_branch=$(git branch --show-current)
    
            # Ensure we have a main branch locally
            if ! git show-ref --verify --quiet refs/heads/main; then
                    echo "❌ No local 'main' branch found. Create it first:"
                    echo "   git checkout -b main upstream/main"
                    return 1
            fi
    
            echo "🔄 Syncing fork with upstream..."
            echo "   Current branch: $current_branch"
    
            # Fetch with error handling
            if ! git fetch upstream; then
                    echo "❌ Failed to fetch from upstream. Check network connection and remote URL."
                    return 1
            fi
    
            echo "📌 Updating local main..."
            if ! git checkout main; then
                    echo "❌ Failed to checkout main branch"
                    return 1
            fi
    
            if ! git reset --hard upstream/main; then
                    echo "❌ Failed to reset main to upstream/main"
                    return 1
            fi
    
            echo "⬆️  Pushing updated main to fork..."
            if ! git push origin main; then
                    echo "❌ Failed to push main to origin. Check push permissions."
                    return 1
            fi
    
            echo "🔀 Rebasing feature branch on updated main..."
            if ! git checkout "$current_branch"; then
                    echo "❌ Failed to checkout $current_branch"
                    return 1
            fi
    
            if ! git rebase main; then
                    echo "❌ Rebase failed due to conflicts. Resolve them and continue:"
                    echo "   1. Edit conflicted files"
                    echo "   2. git add <resolved-files>"
                    echo "   3. git rebase --continue"
                    echo "   Or: git rebase --abort to cancel"
                    return 1
            fi
    
            echo "✅ Ready to work on branch: $current_branch"
    }
    
    ## Sync fork and push feature branch
    gsp() {
            # Safety checks
            if ! git rev-parse --git-dir >/dev/null 2>&1; then
                    echo "❌ Not in a git repository"
                    return 1
            fi
    
            local git_dir=$(git rev-parse --git-dir)
            if [[ -f "$git_dir/rebase-merge/interactive" ]] || [[ -d "$git_dir/rebase-apply" ]] || [[ -f "$git_dir/MERGE_HEAD" ]]; then
                    echo "❌ Git operation in progress. Complete or abort first."
                    return 1
            fi
    
            if ! git diff-index --quiet HEAD -- 2>/dev/null; then
                    echo "❌ You have uncommitted changes. Commit or stash them first:"
                    git status --porcelain
                    return 1
            fi
    
            if ! git remote get-url upstream >/dev/null 2>&1; then
                    echo "❌ No 'upstream' remote found"
                    return 1
            fi
    
            if ! git remote get-url origin >/dev/null 2>&1; then
                    echo "❌ No 'origin' remote found"
                    return 1
            fi
    
            local current_branch=$(git branch --show-current)
    
            # Prevent pushing from main
            if [[ "$current_branch" == "main" ]]; then
                    echo "❌ Cannot push from main branch. Switch to your feature branch first:"
                    echo "   git checkout <your-feature-branch>"
                    return 1
            fi
    
            # Show what we're about to do
            echo "⚠️  About to sync and push branch: $current_branch"
            echo "   This will:"
            echo "   • Fetch latest changes from upstream"
            echo "   • Rebase your branch on updated main"
            echo "   • Force-push to your fork (updates PR)"
            echo ""
    
            read -p "Continue? [y/N]: " -n 1 -r
            echo
    
            if [[ ! $REPLY =~ ^[Yy]$ ]]; then
                    echo "❌ Operation cancelled"
                    return 0
            fi
    
            echo "🔄 Final sync with upstream..."
            if ! git fetch upstream; then
                    echo "❌ Failed to fetch from upstream"
                    return 1
            fi
    
            echo "📌 Updating local main..."
            if ! git checkout main; then
                    echo "❌ Failed to checkout main"
                    return 1
            fi
    
            if ! git reset --hard upstream/main; then
                    echo "❌ Failed to reset main"
                    return 1
            fi
    
            if ! git push origin main; then
                    echo "❌ Failed to push main to origin"
                    return 1
            fi
    
            echo "🔀 Rebasing feature branch..."
            if ! git checkout "$current_branch"; then
                    echo "❌ Failed to checkout $current_branch"
                    return 1
            fi
    
            if ! git rebase main; then
                    echo "❌ Rebase failed. Resolve conflicts and try again:"
                    echo "   git add <resolved-files> && git rebase --continue"
                    echo "   Then run 'gsp' again"
                    return 1
            fi
    
            echo "🚀 Pushing feature branch to fork..."
            if ! git push origin "$current_branch" --force-with-lease; then
                    echo "❌ Failed to push to origin. The branch may have been updated."
                    echo "   Run 'git pull origin $current_branch' and try again"
                    return 1
            fi
    
            echo "✅ Feature branch $current_branch successfully pushed to fork"
    }
    
  • nimpnin@sopuli.xyz
    link
    fedilink
    arrow-up
    4
    ·
    2 months ago

    Since 720p downloading isn’t really available on yt-dlp anymore, I made an alias for it

    alias yt720p="yt-dlp -S vcodec:h264,fps,res:720,acodec:m4a"
    
  • ter_maxima@jlai.lu
    link
    fedilink
    arrow-up
    4
    ·
    2 months ago

    alias ed=$EDITOR

    Extremely convenient on a qwerty keyboard.

    This should probably be a default nowadays. Does even a single person here use the real ed ?

  • mina86@lemmy.wtf
    link
    fedilink
    English
    arrow-up
    3
    ·
    2 months ago

    For doing stuff in a directory, I use a replacement for cd command.

    For aliases:

    alias +='git add'
    alias +p='git add -p'
    alias +u='git add -u'
    alias -- -='cd -'
    alias @='for i in'
    alias c='cargo'
    alias date='LANG=C date'
    alias diff='cdiff'
    alias gg='git grep -n'
    alias grep='grep --color=auto'
    alias ll='ls -o'
    alias ls='ls -vFT0 --si --color=auto --time-style=long-iso'
    alias rmd='rmdir'
    

    I also have various small scripts and functions:

    • a for package management (think apt but has simplified arguments which makes it faster to use in usual cases),
    • e for opening file in Emacs,
    • g for git,
    • s for sudo.

    And here’s ,:

    $ cat ~/.local/bin/,
    #!/bin/sh
    
    if [ $# -eq 0 ]; then
    	paste -sd,
    else
    	printf '%s\n' "$@" | paste -sd,
    fi