this post was submitted on 15 Jul 2023
27 points (100.0% liked)

Shell Scripting

1348 readers
4 users here now

From Ash, Bash and Csh to Xonsh, Ysh and Zsh; all shell languages are welcome here!

Rules:
  1. Follow Lemmy rules!
  2. Posts must relate to shell scripting. (See bottom of sidebar for more information.)
  3. Only make helpful replies to questions. This is not the place for low effort joke answers.
  4. No discussion about piracy or hacking.
  5. 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!
  6. These rules will change as the community grows.

Keep posts about shell scripting! Here are some guidelines to help:


In general, if your submission text is primarily shell code, then it is welcome here!

founded 1 year ago
MODERATORS
 

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!

you are viewing a single comment's thread
view the rest of the comments
[โ€“] varsock 1 points 1 year ago (1 children)

typeset -a $1=("${(@ps[$2])"${2:-"$(<&0)"}"}")

spoilerSo, 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.

  1. typeset -a: This part declares an array variable.
    • -a flag specifies that the variable is an array.
  2. $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.
  3. The entire expression "${(@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.

[โ€“] gamma 1 points 1 year ago

This one was impressively spot-on.