this post was submitted on 15 Jul 2023
27 points (100.0% liked)
Shell Scripting
1367 readers
1 users here now
From Ash, Bash and Csh to Xonsh, Ysh and Zsh; all shell languages are welcome here!
Rules:
- Follow Lemmy rules!
- Posts must relate to shell scripting. (See bottom of sidebar for more information.)
- Only make helpful replies to questions. This is not the place for low effort joke answers.
- No discussion about piracy or hacking.
- If you find a solution to your problem by other means, please take your time to write down the steps you used to solve your problem in the original post. You can potentially help others having the same problem!
- These rules will change as the community grows.
Keep posts about shell scripting! Here are some guidelines to help:
- Allowed: Release Announcement of a command-line program designed for scripted use (e.g. bash, bats, awk, jq, coreutils/moreutils)
- Allowed: Tutorials on using shell languages or supplementary tools designed for scripted use
- Allowed: Code review/help requests for shell languages or supplementary tools designed for scripted use
- NOT Allowed: Announcement of a CLI or TUI program that is not designed for scripted use (Yes, your fancy Zsh plugin which pretty-prints the date and time using only builtins is very cool, but unless you actually want to discuss the code itself, please check out !commandline instead!)
- NOT Allowed: Domain-specific tutorials that do not involve shell scripting as a core component (e.g. docker-compose, ansible, nix). If you really love one of these, I'm sure there's a community out there ready to talk about them!
- NOT Allowed: Code review requests for non-shell programming languages and configuration languages (e.g. Python, Yaml)
In general, if your submission text is primarily shell code, then it is welcome here!
founded 2 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
Literal explanation
${(%)...}
enable prompt sequences%x
a prompt sequence which expands to the current file being executed:P
resolve symlinks:h
the parent directoryFull 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.
curious to see if AI can decipher? Certainly! bonus that we get so see potentially beneficial shell
Here's all the ones I was considering. I only posted the first two here. I'll add the explanations later.
spoiler
So, overall, this script reads input from $2 or stdin if $2 is not provided, splits it into an array based on the delimiter $2, and then assigns the array to the variable named $1. Note that this script only works in Zsh, not in Bash. Zsh has a more advanced parameter and array system than Bash, so this script can't be directly translated into Bash.typeset -a
: This part declares an array variable.-a
flag specifies that the variable is an array.$1=("${(@ps[$2])"${2:-"$(<&0)"}"}")
:$1
refers to the first argument passed to the script."${2:-"$(<&0)"}"
is an expansion that evaluates to the second argument passed to the script. If the second argument is not provided, it reads input from standard input (<&0 means read from stdin)."${(@ps[$2])"
is an expansion that performs parameter splitting.@
specifies that the expansion should be split into separate array elements.(ps[$2])
is a parameter expansion that performs word splitting on the second argument."${(@ps[$2])"${2:-"$(<&0)"}"}"
is wrapped in parentheses and assigned to the variable specified by$1
.In summary, this script takes two arguments:
$1
represents the name of the array variable, and$2
represents the values to be assigned to that array. It then assigns the array$2
to the variable named by$1
after performing parameter and word splitting on the second argument. If the second argument is not provided, it reads input from standard input.This one was impressively spot-on.
spoiler
The given shell script is written in the Zsh shell syntax. It initializes a local array variabled
with the expansion of a string. Let's break it down step by step:local d=
: This line declares a local variabled
. Thelocal
keyword is used to define variables with local scope, meaning they are only accessible within the current scope, such as within a function or a block of code."${(%):-%~}"
: This part of the script performs string expansion and substitution to populate the arrayd
.%~
is a special parameter expansion in Zsh that expands to the current working directory (tilde expansion).(%):
is another parameter expansion flag that performs splitting and globbing on the value obtained from%~
. It splits the resulting string into separate elements based on the/
delimiter and performs globbing (filename expansion) on each element.For example, if the current working directory is
/path/to/some/directory
, then%~
expands to/path/to/some/directory
, and(%):
splits it into individual components:path
,to
,some
, anddirectory
. If there are any glob patterns present, such as*
or?
, they would be expanded as well.("${(@s[/])${(%):-%~}}")
: This part surrounds the expanded string with parentheses to create an array and stores it in the variabled
. The(@s[/])
syntax is an array flag in Zsh that splits the resulting string into separate elements based on the/
delimiter. Each element represents a directory component obtained from the%~
expansion.In summary, this script initializes the local array variable
d
with the directories present in the current working directory's path. Each directory is stored as a separate element in the arrayd
.It may have gotten some details wrong, but the summary is spot-on.
Corrections
(%)
enables prompt expansion.%~
is a string, which when prompt expanded, is $PWD with tilde expansion.spoiler
The given shell script appears to be written in Zsh, a popular Unix shell. Let's break down the script step by step:print -rn
: This command is used to print the output without a newline character (-n
) and without interpreting any escape sequences (-r
).$termcap[sc]
: It refers to a termcap variablesc
, which stands for "save cursor position." Termcap is a database and library used to control the behavior of terminals.$termcap[sc]
saves the current cursor position.${termcap[ch]//(\%i|\%p1|\%d)}
: This part performs a substitution on the value of the termcap variablech
. The double slashes (//
) indicate a global substitution, and the pattern(\%i|\%p1|\%d)
matches any of the three percent sequences:%i
,%p1
, or%d
. It replaces all occurrences of these sequences with an empty string.$termcap[ct]
: It refers to the termcap variablect
, which stands for "clear to end of line." It clears everything from the cursor position to the end of the current line.${(j::)s}
: This uses parameter expansion to join the array variables
using colons (:
) as separators. The(j::)
flag indicates that colons should be used as separators.$termcap[rc]
: It refers to the termcap variablerc
, which stands for "restore cursor position." It restores the saved cursor position.In summary, this shell script saves the cursor position, performs a substitution on the value of
ch
termcap variable, clears the current line from the cursor position to the end, prints the value of array variables
joined by colons, and finally restores the cursor position. The purpose and context of this script can only be determined based on the larger context or the values of the termcap variablessc
,ch
,ct
,s
, andrc
.Corrections
First, a look atman termcap
:(j::)
actually joins with no seperator. The character following thej
is used to capture the separator. Nearly any character or paired bracket can be used, but colons are common. Other ways to write this which might have been more obvious:(j'')
,(j[])
,(j<>)
. To actually join with colons, something like(j.:.)
would have been used.Full context
Zsh agressively sets tabstops to every 8 characters. This is in a function which I trap to theWINCH
signal, to set the termstops to 4 using the$termcap
sequences rather than the external commandtput
:spoiler
The given shell script appears to be written in the Zsh shell syntax. Let's break it down step by step:
[ "${(Oa@)argv[1,-2]}" "${argv[-1]//(#m)[\[\]]/${(#)$((6 ^ #MATCH))}}" ]
: This line encloses the entire script within square brackets[ ]
. In Zsh, square brackets are commonly used for conditional expressions."${(Oa@)argv[1,-2]}"
: This part refers to an expansion of theargv
array, which typically holds command-line arguments passed to the script. Here's what the individual components mean:${(Oa@)}
: This is a parameter expansion flag in Zsh that sorts the elements of the array in ascending order and expands each element as separate words. The@
symbol is used to indicate the array variableargv
.argv[1,-2]
: This is array slicing syntax that extracts a sub-array of elements from index 1 to the second-to-last element (-2
). It excludes the last element, which is assumed to be the final argument.In summary, this part expands and sorts the elements of the
argv
array, excluding the last argument."${argv[-1]//(#m)[\[\]]/${(#)$((6 ^ #MATCH))}}"
: This part refers to another expansion of theargv
array, specifically targeting the last element (argv[-1]
). Here's what the individual components mean:"${argv[-1]//pattern/replacement}"
: This is a parameter expansion that performs pattern substitution within the last element of theargv
array.(#m)
: This is an extended globbing flag in Zsh that enables multiline mode for pattern matching. It allows patterns to match across multiple lines.[\[\]]
: This is the pattern to match. It matches any occurrence of square brackets ([
or]
)./${(#)$((6 ^ #MATCH))}}
: This is the replacement part of the substitution. It calculates the bitwise XOR (^
) of 6 and the matched pattern (#MATCH
), and uses(())
to perform arithmetic expansion. The(#)
flag is used to indicate that the result should be expanded.In summary, this part performs a substitution on the last element of the
argv
array, replacing any occurrence of square brackets with the result of a bitwise XOR operation between 6 and the matched pattern.Overall, the script appears to process command-line arguments, sort and manipulate them, and then enclose the result in a conditional expression for further evaluation or use. The exact purpose or context of the script can only be determined by understanding its broader context and usage.
Corrections
O
is descending order.o
is ascending order. In particular(Oa)
keeps the array order, but flips it.Not here. As a PE flag,
@
puts array elements in separate words, even if the parameter is enclosed in quotes.The
#MATCH
gives the codepoint of the (first) character in$MATCH
. The(#)
flag turns codepoints into characters.Full context
This is in a joke function called]
, which is like[
but you have to specify the elements in reverse order and end it with a[
. This uses bit-fiddling to swap[
and]
in the last parameter because I'm a masochist.spoiler
The given script appears to be written in the Zsh shell syntax. Let's break it down step by step:
set --
: This command sets the positional parameters of the script. In Zsh, the--
option is used to signify the end of options and the beginning of positional parameters."${@[0,eoo]:/(#m)^-*/${MATCH:a}}"
: This part refers to the expansion of the positional parameters, specifically targeting the elements from index 0 to the end of options offset (eoo
). Here's what the individual components mean:${@[0,eoo]}
: This refers to a sub-array of positional parameters from index 0 toeoo
. It extracts the elements corresponding to command-line options./(#m)^-*
: This is a pattern match within a substitution. It matches any occurrences of hyphens (-
) at the beginning of each element. The(#m)
flag enables multiline mode for pattern matching.${MATCH:a}
: This is the replacement part of the substitution. It expands the matched pattern (${MATCH}
) and applies the:a
modifier, which removes leading hyphens from the matched string.In summary, this part removes leading hyphens from the command-line options.
"${@[eoo+1,-1]:a}"
: This part refers to the expansion of the positional parameters, specifically targeting the elements from the end of options offset (eoo
+ 1) to the last element. Here's what the individual components mean:${@[eoo+1,-1]}
: This refers to a sub-array of positional parameters from the end of options offset (eoo
+ 1) to the last element. It extracts the arguments that come after the command-line options.:a
: This applies the:a
modifier, which removes leading hyphens from each element.In summary, this part removes leading hyphens from the command-line arguments that come after the options.
Overall, the script modifies the command-line options and arguments by removing leading hyphens. The modified values are then set as the new positional parameters using the
set
command. The exact purpose or context of the script can only be determined by understanding its broader context and usage.Corrections
It impressively identified exactly whateoo
meant, and handled the array splicing, but it tripped over Zsh's globbing syntax.:
in${foo:/pat/repl}
requirespat
to match the whole element^
actually negates the match, rather than anchors it to the start.^-*
matches any element not beginning with a hyphen.(#m)
flag captures the whole match in the parameter$MATCH
.${MATCH:a}
transforms relative paths toa
bsolute paths.Full context
I use this as a wrapper aroundnvim --remote
to make sure any non-options (i.e.: files) I pass have absolute paths rather than relative paths.I posted interpretations to the remaining ones. I did not have time to massage the prompts or verify the answers. I assume you know what they do and can comment on the accuracy. I am rate limited and had to use a lower tier model, As free up more queries I can re-do some or have it expand on what it's purpose and usefulness might be.