Hi I fork and customize (https://www.putorius.net/create-multiple-choice-menu-bash.html). It is part of automated building script for my project. I wonder how to redirect the answer to different lines (e.g Debian building script starts in line 20 etc.) instead splitting into various files?
#!/bin/sh
PS3='Choose your building platform: '
OS=("Debian" "Fedora" "Arch Linux" "Quit")
select fav in "${OS[@]}"; do
case $fav in
"Debian")
/bin/sh debian.sh
;;
"Fedora")
/bin/sh fedora.sh
;;
"Arch Linux")
/bin/sh arch_linux.sh
;;
"Quit")
echo "Aborting..."
exit
;;
*) echo "invalid option $REPLY";;
esac
done
Because it comes handy that you can write the code in single file instead of splitting into multiple files.
3
Answers
You can define shell functions:
In your case you can define three different functions, one for each build target and then call them:
Source: https://www.tutorialspoint.com/unix/unix-shell-functions.htm
One approach is to set some flag. Something like:
Or depending on the use case one can embed the flag in the loop.
I *VERY STRONGLY* encourage you to pay attention to William Pursell's comments
, and use areop-enap’s functions solution, or Jetchisel’s simple blocks, both of which are quite straightforward and elegant. Do not fall into the trap of embedding for the sake of whimsy.If you want to include several files in one file, use a tool like
tar
. If it has to be an executable, tryzip
.There are, however, some (few) cases where being able to have a script completely contain an entire data file is useful.
For those RARE times when another entire file needs to be encoded into your script, put the files in something like base64-encoding. Decode the ones you need to their own files at runtime, or even to a pipe. (Do NOT use offsets. I’ve had to deal with that nightmare…)
The code below only parses the files it needs. If you ask for "perl" it won’t even hit the section with the embedded bash file. (I’m not sure of how the interpreter might pre-parse and optimize, but I don’t think this method will allocate retained memory the way assigning these to variables would.)
The one advantage to this method is that it lets you embed arbitrary executables such as compiled C code right into the script, but that is at best a somewhat dubious advantage…
There are a lot of other issues to address –
You get the idea.
For the record, in case it matters, this was done on GitBash under windows. Your version might have to make a few refinements.