Sample Header Ad - 728x90

Unix & Linux Stack Exchange

Q&A for users of Linux, FreeBSD and other Unix-like operating systems

Latest Questions

9 votes
3 answers
25747 views
How to unset range of array in Bash
I'm trying to delete range of array element but it's fail.. My array root@ubuntu:~/work# echo ${a[@]} cocacola.com airtel.com pepsi.com Print 0-1 array looks ok root@ubuntu:~/work# echo ${a[@]::2} cocacola.com airtel.com Now I'm trying to delete only these element using : root@ubuntu:~/work# unset a...
I'm trying to delete range of array element but it's fail.. My array root@ubuntu:~/work# echo ${a[@]} cocacola.com airtel.com pepsi.com Print 0-1 array looks ok root@ubuntu:~/work# echo ${a[@]::2} cocacola.com airtel.com Now I'm trying to delete only these element using : root@ubuntu:~/work# unset a[@]::2 root@ubuntu:~/work# echo ${a[@]} It's delete whole array.. What I'm doing wrong ? I found other way of deleting range of array but why above things is not working ? for ((i=0; i<2; i++)); do unset a[$i]; done EDIT I had also tried but no luck unset -v 'a[@]::2'
Rahul Patil (25515 rep)
Apr 30, 2013, 04:02 PM • Last activity: Jul 28, 2025, 04:59 PM
5 votes
3 answers
3894 views
How do I join an array of strings where each string has spaces?
My bash script: #!bin/bash MY_ARRAY=("Some string" "Another string") function join { local IFS="$1"; shift; echo -e "$*"; } join "," ${MY_ARRAY[@]} I want the output to be: `Some string,Another string`. Instead, I get `Some,string,Another,string`. What must I change to get the result I want?
My bash script: #!bin/bash MY_ARRAY=("Some string" "Another string") function join { local IFS="$1"; shift; echo -e "$*"; } join "," ${MY_ARRAY[@]} I want the output to be: Some string,Another string. Instead, I get Some,string,Another,string. What must I change to get the result I want?
Username (899 rep)
Aug 30, 2017, 10:22 PM • Last activity: Jul 17, 2025, 06:30 AM
3 votes
3 answers
2427 views
Mapfile not removing trailing newline
Sample Data: Tab separated file (TSV) ``` a.1.58 fadado/CSV https://github.com/fadado/CSV a.1.63 jehiah/json2csv https://github.com/jehiah/json2csv a.1.80 stedolan/jq https://github.com/stedolan/jq/issues/370 ``` Following selects one record using `fzf`, and stores 2nd and 3rd column to an array Lin...
Sample Data: Tab separated file (TSV)
a.1.58	fadado/CSV	https://github.com/fadado/CSV 
a.1.63	jehiah/json2csv	https://github.com/jehiah/json2csv 
a.1.80	stedolan/jq	https://github.com/stedolan/jq/issues/370 
Following selects one record using fzf, and stores 2nd and 3rd column to an array Link:
mapfile -d $'\t' -t Link < <(awk 'BEGIN{FS="\t"; OFS="\t"} {print $2,$3}' "${SessionP}" | fzf)
## Issue In the above command I have used -t option of mapfile, but echo "${Link}" prints a trailing new line! **Why is it not getting eliminated?** ## Reference - [mapfile Man Page - Linux - SS64.com](https://ss64.com/bash/mapfile.html)
Porcupine (2156 rep)
Jul 26, 2021, 04:35 AM • Last activity: May 30, 2025, 10:52 PM
6 votes
1 answers
2967 views
Split zsh array from subshell by linebreak
I would like to instantiate a zsh array from a subshell myarray=($(somecommand) and I check if I received what I wanted with for element in $myarray ; do echo "===" ; echo $element ; echo "---" ; done By default I see that whitespaces (spaces and line breaks) are used to separate elements. I also fo...
I would like to instantiate a zsh array from a subshell myarray=($(somecommand) and I check if I received what I wanted with for element in $myarray ; do echo "===" ; echo $element ; echo "---" ; done By default I see that whitespaces (spaces and line breaks) are used to separate elements. I also found that I can use ${(s:-:)"$(somecommand)"} to separate by -, in which case spaces and line breaks do not break elements (i.e. array elements can contain line breaks). So far I fail to split at line breaks only. I.e. if somecommand returns Alice Bob Arthur C Clarke Neo Thomas Anderson I want my above for loop to print: === Alice --- === Bob --- === Arthur C Clarke --- === Neo --- === Thomas Anderson --- How do I achieve that? (And possibly pointers where to look that up in the manual.)
pseyfert (890 rep)
Aug 6, 2018, 09:19 AM • Last activity: May 20, 2025, 05:02 PM
0 votes
3 answers
77 views
Making each word in a text file an item in a bash array
I have a string of text and spaces which looks like this: macOS windows arch-linux ubuntu_linux I want to append each item (with whitespace denoting a break between items) to a bash array. How do I do this?
I have a string of text and spaces which looks like this: macOS windows arch-linux ubuntu_linux I want to append each item (with whitespace denoting a break between items) to a bash array. How do I do this?
EmberNeurosis (5 rep)
Apr 29, 2025, 01:22 AM • Last activity: Apr 29, 2025, 07:14 AM
4 votes
1 answers
101 views
How to split output of a shell command on spaces while taking into account quoting?
I have a command that produces a list of arguments, quoting then if neccesary (https://docs.python.org/3/library/shlex.html#shlex.quote). I need them to pass them as command arguments in a `zsh` script (or equivalently, to parse them into an array), which means to split the output on spaces while ta...
I have a command that produces a list of arguments, quoting then if neccesary (https://docs.python.org/3/library/shlex.html#shlex.quote) . I need them to pass them as command arguments in a zsh script (or equivalently, to parse them into an array), which means to split the output on spaces while taking the quoting into account. For example, if the output of my command is foo " bar " baz, I want to parse this into a zsh array equivalent to ('foo' ' bar ' 'baz').
Petr (1776 rep)
Apr 8, 2025, 06:34 PM • Last activity: Apr 8, 2025, 07:27 PM
1 votes
4 answers
140 views
Need shell script help - processing the same option multiple times
So I've ran into a bit of a wall, I have an option in my script that calls a function which allows me to specify a file/directory and then I want to parse that output into a menu tool (using dmenu in this case) to select which file is the one I want specifically and continue working with that select...
So I've ran into a bit of a wall, I have an option in my script that calls a function which allows me to specify a file/directory and then I want to parse that output into a menu tool (using dmenu in this case) to select which file is the one I want specifically and continue working with that selection as a variable in the same script. This works fine if it's just one file or directory, but I want to be able to use the option multiple times and then parse all of that output at once to dmenu. Here's a snippet
fileSelection () {
    if [ -d "${OPTARG}" ]; then find "${OPTARG}" -type f; fi;
    if [ -f "${OPTARG}" ]; then printf '%s\n' "${OPTARG}"; fi;
}

while getopts "f:" option; do
   case "${option}" in
       f) file="$(fileSelection|dmenu)";;
   esac
done
And like I said this works if I do: myscript -f file or myscript -f directory but I was hoping to also be able to do this: myscript -f file1 -f file2 The problem is, since the function is called consecutively I can't parse the output into dmenu like that, because it doesn't invoke dmenu with options file1 and file2, but first with file1 and then with file2, I hope this makes sense. There might be some really simple solution I am missing, I've thought about simply writing the output into a file and then parsing that which might work, but I'd like to avoid piping to files if possible. I am also trying to keep it POSIX compliant, and would appreciate answers that follow that.
hollowillow (11 rep)
Mar 18, 2025, 10:09 PM • Last activity: Mar 20, 2025, 07:58 PM
8 votes
3 answers
1169 views
Unary test -v on an array element
In bash, the conditional expression with the unary test `-v myvariable` tests wether the variable `myvariable` has been set. Note that `myvariable` should not be expanded by prefixing it with a dollar, so **not** `$myvariable`. Now I find that for array elements the conditional expression `-v myarra...
In bash, the conditional expression with the unary test -v myvariable tests wether the variable myvariable has been set. Note that myvariable should not be expanded by prefixing it with a dollar, so **not** $myvariable. Now I find that for array elements the conditional expression -v myarray[index] works well too, without the full expansion syntax ${myarray[$index]}. Try this: myarray=myvalue for i in 1 2 3 do [ -v myarray\[i] ] && echo element $i is set done (note the escape \[ to prevent globbing, as alternative to using quotes) gives the desired output: element 2 is set **Question** Is this behaviour safe to use *aka* is this documented behaviour? **Addendum** After reading the answer https://unix.stackexchange.com/a/677920/376817 of Stéphane Chazelas, I expanded my example: myarray=val myarray=val myarray=val myarray=val myarray=val myarray="" myarray="" unset myarray myarray myarray touch myarray4 myarrayi myarray4=val myarrayi=val then for i in {0..7}; do [ -v myarray\[i] ] && echo element $i is set; done gives element 1 is set element 2 is set element 6 is set Without quoting or escaping the index expression [i] : for i in {0..7}; do [ -v myarray[i] ] && echo element $i is set; done gives element 0 is set element 1 is set element 2 is set element 3 is set element 4 is set element 5 is set element 6 is set element 7 is set The same with the variable myarrayi unset : unset myarrayi for i in {0..7}; do [ -v myarray[i] ] && echo element $i is set; done gives %nothing% And finally with expansion of the index as $i (still without quoting or escaping the bracket) : for i in {0..7}; do [ -v myarray[$i] ] && echo element $i is set; done it gives element 1 is set element 2 is set element 4 is set because ls -l myarray* shows -rw-rw-r-- 1 me us 0 nov 17 15:37 myarray4 -rw-rw-r-- 1 me us 0 nov 17 15:37 myarrayi
db-inf (333 rep)
Nov 17, 2021, 11:01 AM • Last activity: Mar 15, 2025, 05:56 PM
5 votes
4 answers
882 views
Pass multiple files as a single option
I'm trying to build a wrapper to execute a tool multiple times, then concatenate some of the results. I'd like to pass two sets of files to my wrapper script, then run the tool for each pair of files. I'd like it to behave like this: `multitool.sh -a a*.txt -b b*.txt` (expanding the wildcards to mat...
I'm trying to build a wrapper to execute a tool multiple times, then concatenate some of the results. I'd like to pass two sets of files to my wrapper script, then run the tool for each pair of files. I'd like it to behave like this: multitool.sh -a a*.txt -b b*.txt (expanding the wildcards to match all files available) Then inside multitool.sh, I run the tool on a1.txt b1.txt, a2.txt b1.txt, a1.txt b2.txt, a2.txt b2.txt, etc, with variable numbers of a and b files. I followed [this](https://www.redhat.com/en/blog/arguments-options-bash-scripts) tutorial explaining the basics of option handling, and I'm able to use getops to handle a -h, but nothing else. Here is where I'm at now:
#!/bin/bash


while getopts ":hpg:" option; do
	case $option in 
		h) # display help
			echo "-h to print this help and exit, -p is peak files, -g is bedgraph files."
			exit;;
		p) # get list of peak files to process
			l_peaks=$OPTARG;;
		g) # get list of bedgraph files to process
			l_bgraphs=$OPTARG;;
		\?) # Invalid option
			echo "Error! Invalid option!"
			echo "-h to print this help and exit, -p is peak files, -g is bedgraph files."
			exit;;
	esac
done

echo "$l_peaks"
echo "$l_bgraphs"
I'm working with a team who aren't particularly computer literate, so if I can keep the wrapper to a simple one line execution, that would be best. How can I pass these lists of files as one option each?
Whitehot (245 rep)
Feb 24, 2025, 01:09 PM • Last activity: Feb 25, 2025, 07:08 AM
10 votes
5 answers
35006 views
Bash: split multi line input into array
I've got a file with strings and base64 encoded data over multiple lines, that are sepearated by a comma. Example: 1,meV9ivU4PqEKNpo5Q2u2U0h9owUn4Y8CF83TTjUNWTRQs7dEgVxnsMgf4lvg9kvxcIaM3yB4Ssim z46M/C7YlovNUmrjOByhV1SCb/bGyv1yL7SYFnw1GHbYjdH0b6UZ7nQzJHU6VmwMo0V77vFNy6nx rmJZ4KqW9EcjdV1plQmsVXSiZVi61...
I've got a file with strings and base64 encoded data over multiple lines, that are sepearated by a comma. Example: 1,meV9ivU4PqEKNpo5Q2u2U0h9owUn4Y8CF83TTjUNWTRQs7dEgVxnsMgf4lvg9kvxcIaM3yB4Ssim z46M/C7YlovNUmrjOByhV1SCb/bGyv1yL7SYFnw1GHbYjdH0b6UZ7nQzJHU6VmwMo0V77vFNy6nx rmJZ4KqW9EcjdV1plQmsVXSiZVi61+fNOHCMDmVtJ4q097geWxf4bT0/k/yRyRwi5Zr8BC64htVS AdwOSo4PIk7xDLOzLywAYOCDQvD/zuErf1L0e8nHGz2LKdApHdEWB7Y2yM3iZyXuQ4sMx0+oX66+ FxwUulvHj+EpXtLJx5rmV7AUjr/GsNw/1aYAGPCfz0S+//Ic5pXX5rY1fZ96oFGw4a9vRiAmxe/w ZOza6LtwuF+WUHjbIeWTUKKQGgFIM81dwVHHY7xdRnQhK5J0Zf3Xz0GzzZj5/2YFbI8q7lVkJ3ZQ 7Oqt0qdfk3aj+BQhOxmn1F55yACPBZoPUw6K8ExTHHGVGdCEiIDTu5qKHcUwK0hGAZA9Mun5KTO0 gPs9JxF8FJjkQBF7rEa6TP3pH5OwdkATH2uf+Zcmp1t6NbBymXVlsLzWZookVsaT1DNXf1I1H8Xz 8dnfh6Yl63jSr2PAhDrcOqJNM8Z9/XhBGxtlD1ela3nq6N1ErR1Gv1YZKNeNcL7O2Z3Vl2oyyDw=,U2FsdGVkX1/c8rTTO41zVT7gB+KL+n7KoNCgM3vfchOyuvBngdXDGjXTvXTK0jz6 Now, I'd like to split the content into an array, so that each multi-line string is an array element. I tried to use IFS, but that only reads the first line: filecontent=$(cat myfile) IFS=',' read -a myarray <<< "$filecontent" Result: $myarray = 1 $myarray = meV9ivU4PqEKNpo5Q2u2U0h9owUn4Y8CF83TTjUNWTRQs7dEgVxnsMgf4lvg9kvxcIaM3yB4Ssim Expected: $myarray = 1 $myarray = meV9ivU4PqEKNpo5Q2u2U0h9owUn4Y8CF83TTjUNWTRQs7dEgVxnsMgf4lvg9kvxcIaM3yB4Ssim z46M/C7YlovNUmrjOByhV1SCb/bGyv1yL7SYFnw1GHbYjdH0b6UZ7nQzJHU6VmwMo0V77vFNy6nx rmJZ4KqW9EcjdV1plQmsVXSiZVi61+fNOHCMDmVtJ4q097geWxf4bT0/k/yRyRwi5Zr8BC64htVS AdwOSo4PIk7xDLOzLywAYOCDQvD/zuErf1L0e8nHGz2LKdApHdEWB7Y2yM3iZyXuQ4sMx0+oX66+ FxwUulvHj+EpXtLJx5rmV7AUjr/GsNw/1aYAGPCfz0S+//Ic5pXX5rY1fZ96oFGw4a9vRiAmxe/w ZOza6LtwuF+WUHjbIeWTUKKQGgFIM81dwVHHY7xdRnQhK5J0Zf3Xz0GzzZj5/2YFbI8q7lVkJ3ZQ 7Oqt0qdfk3aj+BQhOxmn1F55yACPBZoPUw6K8ExTHHGVGdCEiIDTu5qKHcUwK0hGAZA9Mun5KTO0 gPs9JxF8FJjkQBF7rEa6TP3pH5OwdkATH2uf+Zcmp1t6NbBymXVlsLzWZookVsaT1DNXf1I1H8Xz 8dnfh6Yl63jSr2PAhDrcOqJNM8Z9/XhBGxtlD1ela3nq6N1ErR1Gv1YZKNeNcL7O2Z3Vl2oyyDw= $myarray = U2FsdGVkX1/c8rTTO41zVT7gB+KL+n7KoNCgM3vfchOyuvBngdXDGjXTvXTK0jz6 Could someone help me out here?
Yoda (101 rep)
Feb 3, 2016, 08:47 PM • Last activity: Jan 15, 2025, 08:14 PM
34 votes
7 answers
180128 views
How do I test if an item is in a bash array?
Help for a simple script #!/bin/bash array1=( prova1 prova2 slack64 ) a="slack64" b="ab" if [ $a = $b ] then echo "$a = $b : a is equal to b" else echo "$a = $b: a is not equal to b" fi --- This script simply doesn't work, I want a script which check if slack64 is present in a list(i use an array),a...
Help for a simple script #!/bin/bash array1=( prova1 prova2 slack64 ) a="slack64" b="ab" if [ $a = $b ] then echo "$a = $b : a is equal to b" else echo "$a = $b: a is not equal to b" fi --- This script simply doesn't work, I want a script which check if slack64 is present in a list(i use an array),and simply give me, yes is present,or no. I don't know how to compare an array with a single variable.
elbarna (13690 rep)
Jan 3, 2015, 02:02 AM • Last activity: Jan 14, 2025, 01:48 PM
41 votes
6 answers
59084 views
BASH associative array printing
Is there a way to print an entire array ([key]=value) without looping over all elements? Assume I have created an array with some elements: declare -A array array=([a1]=1 [a2]=2 ... [b1]=bbb ... [f500]=abcdef) I can print back the entire array with for i in "${!array[@]}" do echo "${i}=${array[$i]}"...
Is there a way to print an entire array ([key]=value) without looping over all elements? Assume I have created an array with some elements: declare -A array array=([a1]=1 [a2]=2 ... [b1]=bbb ... [f500]=abcdef) I can print back the entire array with for i in "${!array[@]}" do echo "${i}=${array[$i]}" done However, it seems bash already knows how to get all array elements in one "go" - both keys ${!array[@]} and values ${array[@]}. Is there a way to make bash print this info without the loop? Edit: typeset -p array does that! However I can't remove both prefix and suffix in a single substitution: a="$(typeset -p array)" b="${a##*(}" c="${b%% )*}" Is there a cleaner way to get/print only the key=value portion of the output?
Dani_l (5157 rep)
May 22, 2017, 04:13 PM • Last activity: Jan 5, 2025, 05:02 PM
4 votes
3 answers
19001 views
How to expand array content from its name?
I have an array declare -a arr0=("'1 2 3'" "'4 5 6'") and a variable x=0 Then I create the new variable with the array's name tmp="arr$x" and I'd like to be able to expand `arr0` content from this `tmp` variable like this newArr=( "${!tmp}" ) and to use `newArr` like the ordinary array, e.g. use ind...
I have an array declare -a arr0=("'1 2 3'" "'4 5 6'") and a variable x=0 Then I create the new variable with the array's name tmp="arr$x" and I'd like to be able to expand arr0 content from this tmp variable like this newArr=( "${!tmp}" ) and to use newArr like the ordinary array, e.g. use indices etc. --- But when I try print it now, it looks like this: $ echo ${newArr[@]} '1 2 3' Only the first element is stored and I don't know, how to fix it. I've also tried to create newArr like this newArr=( "${!tmp[@]}" ) but then it's even worse - only 0 is printed. $ echo ${newArr[@]} 0 --- So, do you know, how to use an array if its name is stored in some other variable?
Eenoku (1245 rep)
Mar 8, 2017, 11:44 AM • Last activity: Jan 3, 2025, 07:16 AM
0 votes
2 answers
610 views
Why do these rsync filter args fail in bash when passed in array?
Why does this rsync command work when I give it literally but not when I create it from variables? Here are the variables - first the options I'm passing to rysnc, as an array: $ echo "${options[@]}" -av --prune-empty-dirs -f "- *.flac" -f "- *.WMA" -f "- *.wma" -f "- *.ogg" -f "- *.mp4" -f "- *.m4a...
Why does this rsync command work when I give it literally but not when I create it from variables? Here are the variables - first the options I'm passing to rysnc, as an array: $ echo "${options[@]}" -av --prune-empty-dirs -f "- *.flac" -f "- *.WMA" -f "- *.wma" -f "- *.ogg" -f "- *.mp4" -f "- *.m4a" -f "- *.webm" -f "- *.wav" -f "- *.ape" -f "- *.zip" -f "- *.rar" $ echo ${options} -f $ echo ${options} "- *.wma" Then the source directory, from which rsync is to copy files: $ echo "\"$dir/\"" "/media/test/Ahmad Jamal Trio/Live at the Pershing/" And the target directory, to which rsync is to copy files: $ echo "\"$target_dir\"" "/home/test/mp3/Ahmad Jamal Trio/Live at the Pershing/" Put it all together: $ echo "${options[@]}" "\"$dir/\"" "\"$target_dir\"" -av --prune-empty-dirs -f "- *.flac" -f "- *.WMA" -f "- *.wma" -f "- *.ogg" -f "- *.mp4" -f "- *.m4a" -f "- *.webm" -f "- *.wav" -f "- *.ape" -f "- *.zip" -f "- *.rar" "/media/test/Ahmad Jamal Trio/Live at the Pershing//" "/home/test/mp3/Ahmad Jamal Trio/Live at the Pershing/" That all looks like it should. And indeed, it does work if you give the command literally, like this: $ rsync -av --prune-empty-dirs -f "- *.flac" -f "- *.WMA" -f "- *.wma" -f "- *.ogg" -f "- *.mp4" -f "- *.m4a" -f "- *.webm" -f "- *.wav" -f "- *.ape" -f "- *.zip" -f "- *.rar" "/media/test/Ahmad Jamal Trio/Live at the Pershing/" "/home/test/mp3/Ahmad Jamal Trio/Live at the Pershing/" ./ Ahmad Jamal Trio - Live at the Pershing - 01 - But Not for Me.mp3 Ahmad Jamal Trio - Live at the Pershing - 02 - Surrey With The Fringe On Top.mp3 Ahmad Jamal Trio - Live at the Pershing - 03 - Moonlight In Vermont.mp3 Ahmad Jamal Trio - Live at the Pershing - 04 - Music, Music, Music.mp3 Ahmad Jamal Trio - Live at the Pershing - 05 - No Greater Love.mp3 Ahmad Jamal Trio - Live at the Pershing - 06 - Poinciana.mp3 Ahmad Jamal Trio - Live at the Pershing - 07 - Wood'yn You.mp3 Ahmad Jamal Trio - Live at the Pershing - 08 - What's New.mp3 AlbumArtSmall.jpg AlbumArtLarge.jpg Folder.jpg sent 43,194,376 bytes received 285 bytes 28,796,440.67 bytes/sec total size is 43,182,454 speedup is 1.00 But it fails when I call rsync using the vars as args: $ rsync "${options[@]}" "\"$dir/\"" "\"$target_dir\"" Unknown filter rule: `"- *.flac"' rsync error: syntax or usage error (code 1) at exclude.c(902) [client=3.1.2]
markling (231 rep)
Nov 5, 2019, 10:40 AM • Last activity: Dec 29, 2024, 11:04 AM
38 votes
15 answers
50615 views
Bash - reverse an array
Is there a simple way to reverse an array? #!/bin/bash array=(1 2 3 4 5 6 7) echo "${array[@]}" so I would get: `7 6 5 4 3 2 1` instead of: `1 2 3 4 5 6 7`
Is there a simple way to reverse an array? #!/bin/bash array=(1 2 3 4 5 6 7) echo "${array[@]}" so I would get: 7 6 5 4 3 2 1 instead of: 1 2 3 4 5 6 7
nath (6094 rep)
Dec 25, 2017, 12:53 AM • Last activity: Dec 24, 2024, 07:05 PM
1 votes
2 answers
4772 views
typeset -A is giving error in script
I was using associative arrays in my script, hence I used to declare them by the `typeset -A ` command, and it worked fine in the bash prompt But when I use it in my script, I get the following error ` typeset: -A: invalid option typeset: usage: typeset [-afFirtx] [-p] name[=value] ...` An alternati...
I was using associative arrays in my script, hence I used to declare them by the typeset -A command, and it worked fine in the bash prompt But when I use it in my script, I get the following error ` typeset: -A: invalid option typeset: usage: typeset [-afFirtx] [-p] name[=value] ...` An alternative solution will also be acceptable for me. SIDENOTE: I tried typeset -a but it declares an indexed array. But I want an associative array.
Munai Das Udasin (649 rep)
Aug 13, 2014, 08:11 AM • Last activity: Nov 27, 2024, 10:01 PM
12 votes
7 answers
6406 views
Bash sort array according to length of elements?
Given an array of strings, I would like to sort the array according to the length of each element. For example... array=( "tiny string" "the longest string in the list" "middle string" "medium string" "also a medium string" "short string" ) Should sort to... "the longest string in the list" "also a...
Given an array of strings, I would like to sort the array according to the length of each element. For example... array=( "tiny string" "the longest string in the list" "middle string" "medium string" "also a medium string" "short string" ) Should sort to... "the longest string in the list" "also a medium string" "medium string" "middle string" "short string" "tiny string" (As a bonus, it would be nice if the list sorted strings of the same length, alphabetically. In the above example medium string was sorted before middle string even though they are the same length. But that's not a "hard" requirement, if it over complicates the solution). It is OK if the array is sorted in-place (i.e. "array" is modified) or if a new sorted array is created.
Enterprise (259 rep)
Nov 17, 2018, 08:11 PM • Last activity: Nov 27, 2024, 09:05 AM
24 votes
4 answers
32908 views
How to iterate over array indices in zsh?
In bash we can iterate over index of an array like this ``` ~$ for i in "${!test[@]}"; do echo $i; done ``` where test is an array, say, ``` ~$ test=(a "b c d" e f) ``` so that the output looks like ``` 0 1 2 3 ``` However, when I do the same in zsh I get an error: ``` ➜ ~ for i in "${!test[@]}"; do...
In bash we can iterate over index of an array like this
~$ for i in "${!test[@]}"; do echo $i; done
where test is an array, say,
~$ test=(a "b c d" e f)
so that the output looks like
0
1
2
3
However, when I do the same in zsh I get an error:
➜ ~ for i in "${!test[@]}"; do echo $i; done
zsh: event not found: test[@]
What is going on? What is the proper way of iterating over indices in zsh?
GZ- (357 rep)
Aug 24, 2020, 03:55 PM • Last activity: Nov 18, 2024, 10:37 PM
47 votes
2 answers
18342 views
Is there a reason why the first element of a Zsh array is indexed by 1 instead of 0?
From my experience with modern programming and scripting languages, I believe most programmers are generally accustomed to referring to the first element of an array as index 0 (zero). I'm sure I've heard of languages other than `zsh` starting array indexing on 1 (one); it's okay, as it is equally c...
From my experience with modern programming and scripting languages, I believe most programmers are generally accustomed to referring to the first element of an array as index 0 (zero). I'm sure I've heard of languages other than zsh starting array indexing on 1 (one); it's okay, as it is equally convenient. However, as the previously released and widely used shell scripting languages ksh and bash both use 0, why would someone choose to alter this common convention? There does not seem to be any substantial advantages of using 1 as the first index; then, the only explanation I can think of regarding this somewhat "exclusive feature" to shells would be "they just did this to show off a bit more their cool shell". I don't know much of either zsh or its history, though, and there is a high chance my trivial theory about this does not make any sense. Is there an explanation for this? Or is it just out of personal taste?
deekin (650 rep)
Dec 30, 2015, 05:11 PM • Last activity: Nov 16, 2024, 09:50 AM
47 votes
4 answers
32590 views
Bash: slice of positional parameters
How can I get a slice of `$@` in Bash without first having to copy all positional parameters to another array like this? argv=( "$@" ) echo "${argv[@]:2}";
How can I get a slice of $@ in Bash without first having to copy all positional parameters to another array like this? argv=( "$@" ) echo "${argv[@]:2}";
n.r. (2263 rep)
Jul 7, 2013, 01:12 AM • Last activity: Oct 29, 2024, 06:25 PM
Showing page 1 of 20 total questions