1

What i'm trying to do, is to list all my aliases kinda like this, when i call functions in my bash terminal

$ functions
    functions -> List all functions
    fs -> Determine size of a file or total size of a directory

That ends up happening, is it list every word, so the output looks like this

functions
->
List
all
...

How do iterate get an array like

['functions -> List all functions', 'fs -> Determine size of a file or total size of a directory]

that I can iterate over?

My implementation is listed below

declare -a dotfilesFunctionAlias=()

function appendFunction(){
    dotfilesFunctionAlias+=( "$1->$2" )
}

appendFunction "functions" "List all functions";
function functions(){
    for func in ${dotfilesFunctionAlias[@]}; do
        echo $func;
    done;
}
  • 1
    not sure what any of this has to do with `aliases` ... ??? **assuming** your array is already populated and your only issue at this point is iterating over the array, consider iterating over the array indices, eg: `for idx in ${!dotfilesFunctionAlias[@]}; do echo "${dotfilesFunctionAlias[${idx}]}"; done` – markp-fuso Feb 03 '21 at 16:10
  • 1
    I guess the "aliases" is bad naming :/ That did the job! Thanks ❤️ – Anders Aaen Springborg Feb 03 '21 at 16:41
  • 1
    BTW, in general, `function foo() {` is bad form. Use the POSIX-standard form `foo() {` with no `function`, or the legacy ksh form `function foo {` with no `()`; otherwise, you're incompatible with **both** POSIX and legacy ksh. See https://wiki.bash-hackers.org/scripting/obsolete -- there are relevant entries in both 1st and 3rd tables. – Charles Duffy Feb 03 '21 at 18:04
  • 1
    ...and to reinforce what @xhinne's answer says about `printf` being preferable to `echo`, see the excellent answer by Stephane on [Why is `printf` better than `echo`?](https://unix.stackexchange.com/a/65819/3113) over at [unix.se]. – Charles Duffy Feb 03 '21 at 18:06

1 Answers1

2

You should quote your variables (using an unquoted variable should be the exception):

for func in "${dotfilesFunctionAlias[@]}"; do
    echo "$func";
done;

Without double quotes, ${dotfilesFunctionAlias[@]} is expanded and func takes the value of each word in turn. Double quotes preserve the spaces.

Also, you should be cautious with echo and use printf instead. If the name of one of your functions starts with a valid echo option (-e, -n, etc), then echo "$func" will not work as intended.

Finally, with printf you don't need any loop at all. The following command is enough to print your array.

printf '%s\n' "${dotfilesFunctionAlias[@]}"
xhienne
  • 5,738
  • 1
  • 15
  • 34