Skip Navigation

What are the most inscrutable lines of $SHELL you've ever written?

I'm sure some of you have absolute monstrosities of sigils (I know I do, in my .zshrc alone). Post them without context, and try and guess what other users's lines are. If you want to provide context or guess, use the markdown editor to spoiler-tag your guesses and explanations!

48
48 comments
  • ZDOTDIR="${${(%):-%x}:P:h}"
    
    Literal explanation
    • ${(%)...} enable prompt sequences
    • %x a prompt sequence which expands to the current file being executed
    • :P resolve symlinks
    • :h the parent directory
    Full context

    This line is in my ~/.config/zsh/.zshenv, which I symlink into my home directory. This resolves the symlink and sets $ZDOTDIR to the directory in which my zsh config files actually live, that way they aren't all in my home directory.

    • I'm having a lot of fun taking these inscrutable lines of shell and asking AI to decipher it. Check it out:

      spoiler

      The ZDOTDIR variable in Zsh specifies the directory where the configuration files (.zshrc, .zshenv, .zshlogin, .zshlogout, .zprofile, and .zlogin) are located. By default, this directory is the home directory of the current user. If ZDOTDIR is set, Zsh will use the configuration files from that directory instead of the home directory.

      The script you've posted appears to be setting the ZDOTDIR variable in a complex way, using Zsh parameter expansion and modifiers. Here's the breakdown:

      ${(%):-%x}: This is using Zsh's %(x,y,z) prompt sequence expansion. This construct is used to insert conditional strings in the prompt. However, in this case, the construct is being abused to get the full path of the currently running script (%x), since the else branch (- modifier) of a prompt sequence expansion is always executed.

      :P: This is a Zsh parameter expansion modifier that makes the resulting path absolute by resolving symbolic links. It effectively "canonicalizes" the path.

      :h: Another Zsh parameter expansion modifier, which removes the trailing component from a path, effectively getting the directory portion of a file path. This is equivalent to dirname in a POSIX shell.

      In summary, this script sets ZDOTDIR to the directory of the currently running script, resolving any symbolic links to get the absolute path. This would make Zsh look in that directory for its configuration files, instead of the home directory. It seems to be useful for a script that's bundled with its own Zsh configuration files, and wants to use those instead of the user's configuration

      • Nice! This one was probably the most likely to be found, I actually got this trick from somewhere else online before I understood what it was doing. If you're curious, I've got a few other lines of nested Zsh expansions I picked out but didn't post.

  • Here's one with a bit more context (and actually in Bash, rather than Zsh:

    typeset -A any
    while ((${#anys})); do
    	any[${anys:0:1}]="/${anys:0:1}/!d;"
    	anys=${anys:1}
    done
    anys=${any[*]}
    
    Literal explanation
    • Iterate through the characters in $anys
    • For each character $c, define any[$c] to be the string /$c/!d (e.g.: any[x]='/x/!d')
    • Concatenate the values in ${any[@]}
    Full context

    This is building a sed command to delete all lines which don't contain every character of the string $anys. The associative array and concatenation is to ensure I don't repeat myself when building the command. This is used in a program called dewordle, which prints all remaining words in a dictionary given the current known information in a game of wordle.

  • It's not bash itself that was the complex part exactly, but I have a CI/CD pipeline that generates epub files from markdown. In some cases I have custom designed covers, but where a cover doesn't exist I have a bash script generate one using Imagemagick.

    I wanted to generate the cover in one command to lessen performance impacts and disk I/O, but it took me a few weeks to figure out how to do it all in a single Imagemagick command:

    convert \
        -size 960x1536 \
        -background "${backgroundColor}" \
        -fill "${textColor}" \
        -font "Liberation-Serif" \
        -pointsize 96 \
        -gravity north \
        caption:"${title}" \
        -bordercolor "rgb(0, 0, 0)" \
        -border 2 \
        -bordercolor "${borderColor}" \
        -border 40 \
        -background none \
        -fill "${textColor}" \
        -font "Liberation-Serif" \
        -pointsize 48 \
        -gravity south \
        -geometry +0-800 \
        -annotate +0+40 "${author}" \
        "${destination}cover.jpg"
    

    Eventually it made an abstract sense to me, and I was able to bring it down to two commands and then finally one. This generates a cover with a selected background color (based on content type) and contains title text that will wrap to an inner border.

    I think I had to give up on the author being wrapped, but it's much smaller than the title anyway.

    • Nice work! I've definitely had some fun with convert recently, as you might tell from the community banner.

      spoiler

      It is an image showing the script I used to create it 😛.

  • I don't have a riddle and I can't read Bashisms. In posix shell the most unreadable things are parameter expansion, but compared to the lines OP posted they seems straight forward.

    • I've written multiple Zsh plugins, so I've gotten familiar with a lot of Zsh's features. I've probably read every line in man zshexpn twice by now having referenced it so much.

      Zsh expansions can look gnarly because parameter expansion forms can be nested. Where Bash has to do:

      tmp=${foo%$suffix}
      len=${#tmp}
      

      Zsh can do it in one:

      len=${#${foo%$suffix}}
      

      Once you add PE forms which don't exist in Bash, parameter expansion flags, array subscript flags, globbing qualifiers and modifiers, you can get something which looks absolutely unreadable.

  • reply=( ${(M)dirs:#*/$~pattern}(Noe['REPLY=${(l[3][0])#REPLY:t}'][1]) )
    
    Literal explanation
    • $~pattern interpret globbing characters (like *, ?, or [a-z]) in the parameter $pattern,
    • ${(M)dirs:#*/$~pattern} filter the array $dirs to those matching */$~pattern.
    • ${...}(...) everything in (...) are globbing qualifiers
    • (N) enable nullglob
    • (oe[...]) sort by the result of the shell snippet, where $REPLY is used as input and output
    • ${...REPLY:t} remove all leading path components from $REPLY
    • ${...#REPLY:t} substitute the length of that string
    • ${(l[3][0])#REPLY:t} left-pad with zeroes to a length of 3
    • reply=( ... ) save as $reply
    Full context

    This line is in a function which dynamically expands ~[g:abc] to one of my git repos, choosing the shortest directory matching path/to/abc*, or if no match is found, the shortest matching *abc*. So between /long/path/to/abcdef and /short/abcdefg, it would choose the first one (provided both of those were in the search paths I configured).

  • Feel free to delete this post if you don't feel that this fits though I think the language I use is very similar to bash in some ways (G'MIC). Here's a real-world example of my own code in G'MIC that's pretty much painful to parse:

    command "out2display : skip ${""1=},${""2=},${""3=},${""4=1},${""5=1},${""6=},${""7=},${""8=},${""9=},${""10=} if narg($""1) if $""1 $__bg rv blend alpha fi fi xalp if narg($""6) if narg($""2)&&narg($""3)&&narg($""4)&&narg($""5) {$""4},{$""5},1,{s#0},i(#-1,$""2+x,$""3+y) f. begin(ww=w-1;hh=h-1;);(x<(2+narg($""7))||x>ww-2)||(y<(2+narg($""7))||y>hh-2)?(xor($""6,i)>128?0:255):i j[0] [-1],$""2,$""3 rm. if narg($""8)&&narg($""9)&&narg($""10) if $""8==0||$""8>2 {$""4},{$""5},1,{s#0},i(#0,$__nw+($__min_tile*$""9)-$""2+x-$""4,$""3+y) f. begin(ww=w-1;hh=h-1;);(x<(2+narg($""7))||x>ww-2)||(y<(2+narg($""7))||y>hh-2)?(xor($""6,i)>128?0:255):i j[0] [-1],{$__nw+($__min_tile*$""9)-$""2-$""4},$""3 rm. fi if $""8==1||$""8>2 {$""4},{$""5},1,{s#0},i(#0,$""2+x,$__nh+($__min_tile*$""10)-$""3+y-$""5) f. begin(ww=w-1;hh=h-1;);(x<(2+narg($""7))||x>ww-2)||(y<(2+narg($""7))||y>hh-2)?(xor($""6,i)>128?0:255):i j[0] [-1],$""2,{$__nh+($__min_tile*$""10)-$""3-$""5} rm. fi if $""8==2||$""8>2 {$""4},{$""5},1,{s#0},i(#0,$__nw+($__min_tile*$""9)-$""2+x-$""4,$__nh+($__min_tile*$""10)-$""3+y-$""5) f. begin(ww=w-1;hh=h-1;);(x<(2+narg($""7))||x>ww-2)||(y<(2+narg($""7))||y>hh-2)?(xor($""6,i)>128?0:255):i j[0] [-1],{$__nw+($__min_tile*$""9)-$""2-$""4},{$__nh+($__min_tile*$""10)-$""3-$""5} rm. fi fi fi fi if narg($""7) f[0] begin(ww=w-1;hh=h-1;);(x%$__min_tile==0||y%$__min_tile==0)||(x==ww||y==hh)?$""7:i fi"
    

    That was before I figured out how to properly code in local commands.

  • I have this in my laptop's .bashrc

    PS1='\e[0m\n\e[40m[\e[32m\u\e[37m] [\e[31m\A \d\e[31m] [\e[33m`pwd`\e[37m]\e[K\n\e[K\n\e[1A'
    PS0='\e[0m\n'
    
    hint

    some of the escape sequences move the cursor

    full explanation

    generates the prompt:

    
    [username] [00:01 Thu Jan 1] [/home/username]
    █
    
    

    with a slightly brighter/darker background (depending on terminal colors), while also resetting it to not effect the appearance of command outputs

    • \e[0m\n: new blank line
    • \e[40m: sets the background color for the prompt
    • [: literal text
    • \e[32m\u\e37m: username in green, reset color for brackets
    • ] [: literal text
    • \e[31m\A \d\e[31m: time/date in red, reset color
    • ] [: literal text
    • \e[33mpwd\e[37m: calls pwd, prints it in orange
    • ]: literal text
    • \e[K\n: fill the rest of the prompt line with the background
    • \e[K\n: fill the line where commands are typed with the background
    • \e[1A: move the cursor up so that it's in the background-filled area

    I am colorblind so I may have gotten colors wrong, but that's hardly where the interesting bit is.

    • That doesn't seem sensible. Moving the cursor will confuse bash and you can get the same effect by just omitting the last \n.

      Note that bash 5.0, but not earlier or later versions, is buggy with multiline prompts even if they're correct.

      Your colors should use 39 (or 49) for reset.

      Avoid doing external commands in subshells when there's a perfectly good prompt-expansion string that works.

      You seem to be generating several unnecessary blank lines, though I haven't analyzed them in depth; remember that doing them conditionally is an option, like I do:

      #PS1 built up incrementally before this, including things like setting TTY title for appropriate terminals
      PS0='vvv \D{%F %T%z}\n'
      PS1='^^^ \D{%F %T%z}\n'"$PS1"
      prompt-command-exit-nonzero()
      {
          # TODO map signal names and <sysexits.h> and 126/127 errors?
          # (128 also appears in some weird job-control cases; there are also
          # numerous cases where $? is not in $PIPESTATUS)
          # This has to come first since $? will be invalidated.
          # It's also one of the few cases where `*` is non-buggy for an array.
          local e=$? pipestatus="${PIPESTATUS[*]}"
          # Fixup newline. Note that interactive shells specifically use stderr
          # for the prompt, not stdin, stdout, or /dev/tty
          printf '\e[93;41m%%\e[39;49m%'"$((COLUMNS-1))"'s\r' >&2
          # if e or any pipestatus is nonzero
          if [[ -n "${e/0}${pipestatus//[ 0]}" ]]
          then
              if [[ "$pipestatus" != "$e" ]]
              then
                  local pipestatus_no_SIGPIPE="${pipestatus//141 /}"
                  local color=41
                  if [[ -z "${pipestatus_no_SIGPIPE//[ 0]}" ]]
                  then
                      color=43
                  fi
                  printf '\e[%smexit_status: %s (%s)\e[49m\n' "$color" "$e" "${pipestatus// / | }" >&2
              else
                  printf '\e[41mexit_status: %s\e[49m\n' "$e" >&2
              fi
          fi
      }
      PROMPT_COMMAND='prompt-command-exit-nonzero'
      
      
48 comments