0

I need help figuring out how to run a bash alias or function that randomly chooses another command or alias and runs it.

the list of commands and aliases and function aliases is known beforehand. the size of list is also known.

I have multiple variations of an ascii art stored in aliases.

e.g. ascii-art-colorless-clear ascii-art-colorless-bg ascii-art-colored-clear ascii-art-colored-bg

I dont want to type the whole alias I just want to type ascii-art and have one of the aliases be chosen as random.

each alias is just a simple echo command in this case

EDIT: answer found with help from Gilles Quenot. function needed is select-random-arguement-to-run() { $(shuf -e "$@" -n 1) }

this will select a random alias and run it

alias ascii-art="select-random-arguement-to-run "ascii-art-colorless-clear" "ascii-art-colorless-bg" "ascii-art-colored-clear" "ascii-art-colored-bg""

which needs the select-random-arguement-to-run function defined previously to be in my bashrc file.

2 Answers2

2

What I would do using tools:

$ cat commands.list
rcp
scp
ssh

Code:

$ shuf commands.list | head -n1
ssh # random command

To define a function:

$ myfunc(){ shuf commands.list | head -n1; }

To call the function:

$ myfunc
  • ok shuf is great command to use. and head is not needed. shuf -e command1 command2 ... commandN -n 1 should do the trick. do you know how to use this with a case statement in bash – stacking and exchanging woohoo Nov 07 '22 at 20:40
  • What does a case statement have to do with your question? – glenn jackman Nov 07 '22 at 20:55
  • well I thought it would help to do it that way. if there is an easier way then that is better. – stacking and exchanging woohoo Nov 07 '22 at 21:22
  • I tried doing this and it seems to do the job \shuf -e "echo bye later" "echo hi howdy" -n 1`` do you know a way to do it without backsticks (`) ? – stacking and exchanging woohoo Nov 07 '22 at 21:29
  • @stackingandexchangingwoohoo please stop asking follow up questions in the comments. Instead, edit your question and ask what you really need there. As it stands, your question is still insisting on an alias, and is talking about specific ascii art file names while your answer is all about executing commands. – terdon Nov 08 '22 at 09:55
0

building on top of what Gilles Quenot said (Gilles Quenot's answer)

this is the answer that worked in my bash alias/function

run-random-command() {
    $(shuf -e "$@" -n 1)
}

running $(run-random-command "echo hi" "echo bye" "ls") will either print bye or hi to terminal or run ls and is equivalent to

$(shuf -e "echo hi" "echo bye" "ls" -n 1)

as you may know, shuf returns the text of the code, thus $() is used to run the text that shuf returns.

  • 1
    Please don't use backtcks, there's mostly deprecated. You want $(shuf -e "$@" -n 1) instead. – terdon Nov 08 '22 at 09:54