Do you actually use getopts in your noscripts?
I always see
https://redd.it/1ksm8f2
@r_bash
I always see
getopts in discussions, but in real life most noscripts that I come across are just parsing $@ manually. Curious if anyone actually uses it regularly, or if it's more of a 'looks good in theory' kind of thing.https://redd.it/1ksm8f2
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
Run non bash command from noscript
Hello,
Newbie here, who started bash noscripting. I am trying to call cowsay from a noscript I am working on. It's just a basic noscript which reads input from a user and spits it out with cowsay. However the fails at the cowsay line with error command not found. Cowsay has been added to path as I am able to call it from anywhere in the terminal without issues. How do I get it to run from the noscript?
Thanks.
https://redd.it/1kt0mq1
@r_bash
Hello,
Newbie here, who started bash noscripting. I am trying to call cowsay from a noscript I am working on. It's just a basic noscript which reads input from a user and spits it out with cowsay. However the fails at the cowsay line with error command not found. Cowsay has been added to path as I am able to call it from anywhere in the terminal without issues. How do I get it to run from the noscript?
Thanks.
https://redd.it/1kt0mq1
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
Help parsing a string in Bash
Hi,
I was hopign that i could get some help on how to parse a string in bash.
I woudl like to take an input string and parse it to two different variables. The first variable is TITLE and the second is TAGS.
The properties of TITLE is that it will always appear before tags and can be made of multiple words. The properties of the TAGS is that they may
For example the most complext input string that I can imagine would be somethign like the following
This is the noscript of the input string +These +are +the +tags
The above input string needs to be parsed into the following two variables
TITLE="This is the noscript of the input string"
TAGS="These are the tags"
Can anyone help?
Thanks
https://redd.it/1kt449m
@r_bash
Hi,
I was hopign that i could get some help on how to parse a string in bash.
I woudl like to take an input string and parse it to two different variables. The first variable is TITLE and the second is TAGS.
The properties of TITLE is that it will always appear before tags and can be made of multiple words. The properties of the TAGS is that they may
For example the most complext input string that I can imagine would be somethign like the following
This is the noscript of the input string +These +are +the +tags
The above input string needs to be parsed into the following two variables
TITLE="This is the noscript of the input string"
TAGS="These are the tags"
Can anyone help?
Thanks
https://redd.it/1kt449m
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
need for speed
hello everyone,
let me start by saying that I'm not a coder
I wrote the following fetch noscript with scroll effect just for fun:
>https://codeberg.org/ldm/scr0ll
I also published it on r/unixporn, but I received some comments complaining about the speed...
is this problem due to a badly written noscript? or is bash slow? can the noscript be further optimized?
https://redd.it/1ktghg0
@r_bash
hello everyone,
let me start by saying that I'm not a coder
I wrote the following fetch noscript with scroll effect just for fun:
>https://codeberg.org/ldm/scr0ll
I also published it on r/unixporn, but I received some comments complaining about the speed...
is this problem due to a badly written noscript? or is bash slow? can the noscript be further optimized?
https://redd.it/1ktghg0
@r_bash
Codeberg.org
scr0ll
Exit Code for CLI Applications
I've been doing a lot of devops and bash lately, and I'm dissatisfied with the lack of standards around exit codes. Yes, there are some sensible standards such as exit codes over 68 and 126 mapping to signal and OS related failures, but what about custom exit codes?
Obviously 0 is everything went well, but how do you handle cases where the noscript ran as predicted (without crashing) but a distinct/warning-like outcome took place, and an exit code should inform the user on the kind of error that came accross.
I say this because 1 is the catch-all "something went wrong", but at the same time that means your successful but noteworthy exit codes are separated from 0 since you set them to 2,3,4...
Is there some solution I'm missing? I'm starting to settle towards:
0 - success
1 - catchall error
2-67 - custom output state, successful execution but important enough that automated noscripts will want to know about it.
Take
https://redd.it/1kt9n4c
@r_bash
I've been doing a lot of devops and bash lately, and I'm dissatisfied with the lack of standards around exit codes. Yes, there are some sensible standards such as exit codes over 68 and 126 mapping to signal and OS related failures, but what about custom exit codes?
Obviously 0 is everything went well, but how do you handle cases where the noscript ran as predicted (without crashing) but a distinct/warning-like outcome took place, and an exit code should inform the user on the kind of error that came accross.
I say this because 1 is the catch-all "something went wrong", but at the same time that means your successful but noteworthy exit codes are separated from 0 since you set them to 2,3,4...
Is there some solution I'm missing? I'm starting to settle towards:
0 - success
1 - catchall error
2-67 - custom output state, successful execution but important enough that automated noscripts will want to know about it.
Take
diff for example: 0 means inputs are the same, 1 if different, 2 if trouble. Well for most other programs, 1 means they shit the bed. So I'm a little confused.https://redd.it/1kt9n4c
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
Command to var
Maybe I'm just overly tired.... and the fact that I can't seem to type the right search query so I'm getting nothing.
Suppose I have a stupid long command
and this command will basically replace the base git command in my noscript. I want to be able to assign that long command and be able to call it.
I'll try to provide an example.
For some reason, I can't get it to work.
I also tried it as a function, but when I run it, all I get is the git --help menu
https://redd.it/1ktrn4g
@r_bash
Maybe I'm just overly tired.... and the fact that I can't seem to type the right search query so I'm getting nothing.
Suppose I have a stupid long command
git --work-tree=/path/to/work/tree --git-dir=/path/folder
and this command will basically replace the base git command in my noscript. I want to be able to assign that long command and be able to call it.
I'll try to provide an example.
MY_COMMAND=`git --work-tree=/path/to/work/tree --git-dir=/path/folder`
MY_COMMAND commit -m "new commit"
MY_COMMAND push
For some reason, I can't get it to work.
I also tried it as a function, but when I run it, all I get is the git --help menu
my_command() {
git --work-tree=/path/to/work/tree --git-dir=/path/folder
}
my_command commit -m "new commit"
https://redd.it/1ktrn4g
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
Check out my custom utility noscripts library
I've made a modular repogh-tsilvs-bashlib of utility function noscripts for bash.
Some of it may be useful for:
- Active Podman users
- Frequent Bash users
- Users daily driving Fedora Silverblue
- Developers versioning their code with Git
- ADB users
- And many more!
Would appreciate your feeedback.
gh-tsilvs-bashlib: https://github.com/tsilvs/bashlib
https://redd.it/1ktv7b7
@r_bash
I've made a modular repogh-tsilvs-bashlib of utility function noscripts for bash.
Some of it may be useful for:
- Active Podman users
- Frequent Bash users
- Users daily driving Fedora Silverblue
- Developers versioning their code with Git
- ADB users
- And many more!
Would appreciate your feeedback.
gh-tsilvs-bashlib: https://github.com/tsilvs/bashlib
https://redd.it/1ktv7b7
@r_bash
GitHub
GitHub - tsilvs/bash_utils: My Bash utilities library
My Bash utilities library. Contribute to tsilvs/bash_utils development by creating an account on GitHub.
I need help to be able to capture when Caps Lock is on or off
A while back, I saw a video where they were trying to give Caps Lock more uses, and today it occurred to me that maybe I could open the rofi using `super + Caps_Lock`. I wrote the following quick bash noscript to test my idea, and if I run it from the terminal, it correctly notifies me when it's enabled and when it's not.
```bash
#!/bin/bash
function main() {
(
export DISPLAY=${DISPLAY:-:0}
state=$(xset q | grep "Caps Lock:" | awk '{print $4}')
if [[ "$state" == "on" ]]; then
notify-send "Caps Lock activated"
else
notify-send "Caps Lock deactivated"
fi
)
}
main $@
```
So I added the following rule to my sxhkd configuration to run it:
```bash
super + Caps_Lock
sh ~/Workspace/Playground/caps-lock.sh
```
But when I press super + Caps_Lock, it only takes me to the case where it's enabled, and no key combination takes me to the other case. Do you have any idea what it could be or how I can fix this?
https://redd.it/1kty42l
@r_bash
A while back, I saw a video where they were trying to give Caps Lock more uses, and today it occurred to me that maybe I could open the rofi using `super + Caps_Lock`. I wrote the following quick bash noscript to test my idea, and if I run it from the terminal, it correctly notifies me when it's enabled and when it's not.
```bash
#!/bin/bash
function main() {
(
export DISPLAY=${DISPLAY:-:0}
state=$(xset q | grep "Caps Lock:" | awk '{print $4}')
if [[ "$state" == "on" ]]; then
notify-send "Caps Lock activated"
else
notify-send "Caps Lock deactivated"
fi
)
}
main $@
```
So I added the following rule to my sxhkd configuration to run it:
```bash
super + Caps_Lock
sh ~/Workspace/Playground/caps-lock.sh
```
But when I press super + Caps_Lock, it only takes me to the case where it's enabled, and no key combination takes me to the other case. Do you have any idea what it could be or how I can fix this?
https://redd.it/1kty42l
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
Using tree to ignore a folder
I need to use tree to list all files in a folder and sub-folders and write them to a txt file, but to ignore one specific folder, "Document Scans".
ie. scan all in /media/me/Documents/ but ignore the folder /media/me/Documents/Document Scans/
I have been using the command as below, however it does not exclude the Document Scan Folder. I'm not sure why.
Where am I going wrong?
https://redd.it/1ku6fze
@r_bash
I need to use tree to list all files in a folder and sub-folders and write them to a txt file, but to ignore one specific folder, "Document Scans".
ie. scan all in /media/me/Documents/ but ignore the folder /media/me/Documents/Document Scans/
I have been using the command as below, however it does not exclude the Document Scan Folder. I'm not sure why.
tree -sh /media/me/Documents/* -I /media/me/Documents/Document\ Scans/ > /home/me/TreeList.txtWhere am I going wrong?
https://redd.it/1ku6fze
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
2D Array?
I am trying to make a 2D array in a .sh file to run with bash, the array is defined below:
array=( \
(25 "test1") \
(110 "test2") \
(143 "test3") \
(465 "test4") \
(587 "test5") \
(993 "test6") \
)
I have tried with and without the
file.sh: line 4: syntax error near unexpected token
file.sh: line 6: syntax error near unexpected token
Is there anything blatantly wrong that I'm just not seeing?
https://redd.it/1ku8v3u
@r_bash
I am trying to make a 2D array in a .sh file to run with bash, the array is defined below:
array=( \
(25 "test1") \
(110 "test2") \
(143 "test3") \
(465 "test4") \
(587 "test5") \
(993 "test6") \
)
I have tried with and without the
\ and each time receive the following error: file.sh: line 4: syntax error near unexpected token
('
file.sh: line 4: (25 "test1") \'file.sh: line 6: syntax error near unexpected token
('
file.sh: line 6: (143 "test3") \'Is there anything blatantly wrong that I'm just not seeing?
https://redd.it/1ku8v3u
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
A bash implementation of Tabloid
https://github.com/notweerdmonk/tabloid.bash
https://redd.it/1kuhmr7
@r_bash
https://github.com/notweerdmonk/tabloid.bash
https://redd.it/1kuhmr7
@r_bash
GitHub
GitHub - notweerdmonk/tabloid.bash: A bash implementation of Tabloid, the clickbait programming language
A bash implementation of Tabloid, the clickbait programming language - GitHub - notweerdmonk/tabloid.bash: A bash implementation of Tabloid, the clickbait programming language
Can I evaluate variables in a file without using eval?
Hey everyone,
I'm using env vars as bookmarks for folders I use often. I decided I love fzf's UI, so I wanted to pipe the list of env vars into fzf, but when I'm adding them to an assoc array, they show up as simply strings, without being evaluated.
an example:
I did try moving my bookmarks into it's own file, then sourcing the file, suggested by chatgpt. But I couldn't get it to work. I know eval is a thing,
but seems like I'm not supposed to use eval.
I'd appreciate any advice.
https://redd.it/1kul6ee
@r_bash
Hey everyone,
I'm using env vars as bookmarks for folders I use often. I decided I love fzf's UI, so I wanted to pipe the list of env vars into fzf, but when I'm adding them to an assoc array, they show up as simply strings, without being evaluated.
an example:
BOOKS="${HOME}/Documents/Books/"
I did try moving my bookmarks into it's own file, then sourcing the file, suggested by chatgpt. But I couldn't get it to work. I know eval is a thing,
but seems like I'm not supposed to use eval.
I'd appreciate any advice.
https://redd.it/1kul6ee
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
New Resource: Complete Bash Scripting Course with Real-World DevOps Projects
Hey r/bash ! 👋
After months of development, I just launched my comprehensive Bash Scripting for DevOps course on Udemy. As someone who's spent countless hours doing repetitive server tasks manually (we've all been there!), I wanted to create something that actually teaches practical automation skills.
**What makes this different:**
* 6 modules taking you from basic commands to production-ready noscripts
* Real-world DevOps scenarios (not just toy examples)
* Complete project you can download and study
* Focus on maintainable, debuggable code
**You'll learn to build:**
* Dynamic noscripts with parameters
* Intelligent loops for processing at scale
* Conditional logic for decision-making
* Reusable function libraries
* Log parsing and monitoring systems
Perfect if you're tired of running the same commands over and over, or want to level up your automation game. No advanced prerequisites needed - just basic command line familiarity.
The course includes a complete example project and professional debugging techniques I use daily.
**Course link:** [https://www.udemy.com/course/mastering-bash-noscripts/?referralCode=0C6353B2C97D60937925](https://www.udemy.com/course/mastering-bash-noscripts/?referralCode=0C6353B2C97D60937925)
Happy to answer any questions about the content or approach! What's your biggest automation challenge right now?
https://redd.it/1kv28s7
@r_bash
Hey r/bash ! 👋
After months of development, I just launched my comprehensive Bash Scripting for DevOps course on Udemy. As someone who's spent countless hours doing repetitive server tasks manually (we've all been there!), I wanted to create something that actually teaches practical automation skills.
**What makes this different:**
* 6 modules taking you from basic commands to production-ready noscripts
* Real-world DevOps scenarios (not just toy examples)
* Complete project you can download and study
* Focus on maintainable, debuggable code
**You'll learn to build:**
* Dynamic noscripts with parameters
* Intelligent loops for processing at scale
* Conditional logic for decision-making
* Reusable function libraries
* Log parsing and monitoring systems
Perfect if you're tired of running the same commands over and over, or want to level up your automation game. No advanced prerequisites needed - just basic command line familiarity.
The course includes a complete example project and professional debugging techniques I use daily.
**Course link:** [https://www.udemy.com/course/mastering-bash-noscripts/?referralCode=0C6353B2C97D60937925](https://www.udemy.com/course/mastering-bash-noscripts/?referralCode=0C6353B2C97D60937925)
Happy to answer any questions about the content or approach! What's your biggest automation challenge right now?
https://redd.it/1kv28s7
@r_bash
Udemy
Free Bash Shell Tutorial - Automate Linux with Bash: From Zero to DevOps Pro
Zero to automation hero • Master loops, functions & text processing • Build real DevOps projects that impress - Free Course
Linux Journey is no longer maintained… so I rebuilt it
Hey everyone, Like many of you, I found Linux Journey to be an awesome resource for learning Linux in a fun, approachable way. Unfortunately, it hasn't been actively maintained for a while.
So I decided to rebuild it from scratch and give it a second life. Introducing Linux Path — a modern, refreshed version of Linux Journey with updated content, a cleaner design, and a focus on structured, beginner-friendly learning.
It’s open to everyone, completely free, mobile-friendly, and fully open source. You can check out the code and contribute Here
If you ever found Linux Journey helpful, I’d love for you to take a look, share your thoughts, and maybe even get involved. I'm building this for the community, and your feedback means a lot.
https://redd.it/1ku8adu
@r_bash
Hey everyone, Like many of you, I found Linux Journey to be an awesome resource for learning Linux in a fun, approachable way. Unfortunately, it hasn't been actively maintained for a while.
So I decided to rebuild it from scratch and give it a second life. Introducing Linux Path — a modern, refreshed version of Linux Journey with updated content, a cleaner design, and a focus on structured, beginner-friendly learning.
It’s open to everyone, completely free, mobile-friendly, and fully open source. You can check out the code and contribute Here
If you ever found Linux Journey helpful, I’d love for you to take a look, share your thoughts, and maybe even get involved. I'm building this for the community, and your feedback means a lot.
https://redd.it/1ku8adu
@r_bash
Using history in a noscript
I want to make a simple noscript where history is formated with a date, all of history is redirected into a hist_log.txt file, said file is then greped for the date that was input and the results of the grep are redirected to a date_log.txt file. The issue im facing is when i run to test the noscript history is either ignored or acts like its empty, the needed files are created but since nothing is getting redirected to the first log file theres noting to grep to populate the second file. Using history outside a noscript shows all the entries that should be there.If I manually populate history_log with history > history_log.txt and run the noscript I get the expected results. This is what I'm currently working with
\#!/bin/bash
export HISTTIMEFORMAT='%F %T '
history -a
history -r
history > hist_log.txt
echo Enter a date:
read date
grep "$date" hist_log.txt > "/home/$USER/${date}_log.txt"
echo "Your log is in /home/$USER/${date}_log.txt"
Anyone more experienced that could point me in the right direction to get this to work?
https://redd.it/1kvw09p
@r_bash
I want to make a simple noscript where history is formated with a date, all of history is redirected into a hist_log.txt file, said file is then greped for the date that was input and the results of the grep are redirected to a date_log.txt file. The issue im facing is when i run to test the noscript history is either ignored or acts like its empty, the needed files are created but since nothing is getting redirected to the first log file theres noting to grep to populate the second file. Using history outside a noscript shows all the entries that should be there.If I manually populate history_log with history > history_log.txt and run the noscript I get the expected results. This is what I'm currently working with
\#!/bin/bash
export HISTTIMEFORMAT='%F %T '
history -a
history -r
history > hist_log.txt
echo Enter a date:
read date
grep "$date" hist_log.txt > "/home/$USER/${date}_log.txt"
echo "Your log is in /home/$USER/${date}_log.txt"
Anyone more experienced that could point me in the right direction to get this to work?
https://redd.it/1kvw09p
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
Conflict between ble.sh and starship prompt causing doubling of prompt on terminal startup
https://redd.it/1kwbwmf
@r_bash
https://redd.it/1kwbwmf
@r_bash
Unable to add a function to bashrc due to syntax issues
here is what I'm trying to add to my bashrc:
ls () {
if [ "$*" == *"--no-details"* ]; then
local args=("${@/--no-details/}")
eza -l --no-permissions --no-filesize --no-user --no-time "${args@}"
else
eza -l "$@"
fi
}
when I save the file and source it, i get this error:
bash: /home/vrin/.bashrc: line 19: syntax error near unexpected token
any idea why this happens? all functions I've seen online use the same syntax (eg, function name, space, brackets, space, braces). any tips are appreciated, tia!
https://redd.it/1kwfyzw
@r_bash
here is what I'm trying to add to my bashrc:
ls () {
if [ "$*" == *"--no-details"* ]; then
local args=("${@/--no-details/}")
eza -l --no-permissions --no-filesize --no-user --no-time "${args@}"
else
eza -l "$@"
fi
}
when I save the file and source it, i get this error:
bash: /home/vrin/.bashrc: line 19: syntax error near unexpected token
('
bash: /home/vrin/.bashrc: line 19: ls () {'any idea why this happens? all functions I've seen online use the same syntax (eg, function name, space, brackets, space, braces). any tips are appreciated, tia!
https://redd.it/1kwfyzw
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
How I Made Stow Easy
I used git bare to manage my dotfiles and wanted to also try out gnu stow as per recommendations online.
Every time I use it I have to relearn it and manually move files which I hate so I made a bash noscript to make things easier.
I tried to make the noscript readable (with comments explaining some parts), added checks along the way to prevent unintended behavior and ran
Here's the repo link
Feel free to create an issue if you find something wrong with the noscript :)
https://redd.it/1kwiho9
@r_bash
I used git bare to manage my dotfiles and wanted to also try out gnu stow as per recommendations online.
Every time I use it I have to relearn it and manually move files which I hate so I made a bash noscript to make things easier.
I tried to make the noscript readable (with comments explaining some parts), added checks along the way to prevent unintended behavior and ran
shellcheck against it to fix some errors (It still tells me to change some parts but I'm comfortable with how it is rn)Here's the repo link
Feel free to create an issue if you find something wrong with the noscript :)
https://redd.it/1kwiho9
@r_bash
GitHub
GitHub - skynetcat/udots: Easily Stow Your Dotfiles
Easily Stow Your Dotfiles. Contribute to skynetcat/udots development by creating an account on GitHub.
can't create function in bashrc
here is what I'm trying to add to my bashrc:
ls () {
if [ "$*" == *"--no-details"* ]; then
local args=("${@/--no-details/}")
eza -l --no-permissions --no-filesize --no-user --no-time "${args@}"
else
eza -l "$@"
fi
}
when I save the file and source it, i get this error:
bash: /home/vrin/.bashrc: line 19: syntax error near unexpected token
any idea why this happens? all functions I've seen online use the same syntax (eg, function name, space, brackets, space, braces). what could be wrong. here's the complese bashrc for reference https://pastebin.com/9ejjs3BK
https://redd.it/1kwfto2
@r_bash
here is what I'm trying to add to my bashrc:
ls () {
if [ "$*" == *"--no-details"* ]; then
local args=("${@/--no-details/}")
eza -l --no-permissions --no-filesize --no-user --no-time "${args@}"
else
eza -l "$@"
fi
}
when I save the file and source it, i get this error:
bash: /home/vrin/.bashrc: line 19: syntax error near unexpected token
('
bash: /home/vrin/.bashrc: line 19: ls () {'any idea why this happens? all functions I've seen online use the same syntax (eg, function name, space, brackets, space, braces). what could be wrong. here's the complese bashrc for reference https://pastebin.com/9ejjs3BK
https://redd.it/1kwfto2
@r_bash
Pastebin
## ~/.bashrc## If not running interactively, don't do anything[[ $- != - Pastebin.com
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Manual argument parsing: need a good template
Looking for a good general-purpose manual argument parsing implementation. If I only need short-style options, I would probably stick to to `getopts` but sometimes it's useful to long-style options because they are easier to remember. I came across the following ([source](https://medium.com/@Drew_Stokes/bash-argument-parsing-54f3b81a6a8f)) (I would probably drop short-style support here unless it's trivial to add it because e.g. `-ab` for `-a -b` is not supported so it's not intuitive to not support short-style options fully):
#!/bin/bash
PARAMS=""
while (( "$#" )); do
case "$1" in
-a|--my-boolean-flag)
MY_FLAG=0
shift
;;
-b|--my-flag-with-argument)
if [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
MY_FLAG_ARG=$2
shift 2
else
echo "Error: Argument for $1 is missing" >&2
exit 1
fi
;;
-*|--*=) # unsupported flags
echo "Error: Unsupported flag $1" >&2
exit 1
;;
*) # preserve positional arguments
PARAMS="$PARAMS $1"
shift
;;
esac
done
# set positional arguments in their proper place
eval set -- "$PARAMS"
Can this be be improved? I don't understand why `eval` is necessary and an array feels more appropriate than concatenating `PARAMS` variable (I don't think the intention was to be POSIX-compliant anyway with `(( "$#" ))`. Is it relatively foolproof? I don't necessarily want a to use a non-standard library that implements this, so perhaps this is a good balance between simplicity (easy to understand) and provides the necessary useful features.
Sometimes my positional arguments involve filenames so it can technically start with a `-` (dash)--I'm not sure if that should be handled even though I stick to standard filenames (like those without newlines, etc.).
P.S. I believe one can hack `getopts` to support long-style options but I'm not sure if the added complexity is worth it over the seemingly more straightforward manual-parsing for long-style options like above.
https://redd.it/1kwez5l
@r_bash
Looking for a good general-purpose manual argument parsing implementation. If I only need short-style options, I would probably stick to to `getopts` but sometimes it's useful to long-style options because they are easier to remember. I came across the following ([source](https://medium.com/@Drew_Stokes/bash-argument-parsing-54f3b81a6a8f)) (I would probably drop short-style support here unless it's trivial to add it because e.g. `-ab` for `-a -b` is not supported so it's not intuitive to not support short-style options fully):
#!/bin/bash
PARAMS=""
while (( "$#" )); do
case "$1" in
-a|--my-boolean-flag)
MY_FLAG=0
shift
;;
-b|--my-flag-with-argument)
if [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
MY_FLAG_ARG=$2
shift 2
else
echo "Error: Argument for $1 is missing" >&2
exit 1
fi
;;
-*|--*=) # unsupported flags
echo "Error: Unsupported flag $1" >&2
exit 1
;;
*) # preserve positional arguments
PARAMS="$PARAMS $1"
shift
;;
esac
done
# set positional arguments in their proper place
eval set -- "$PARAMS"
Can this be be improved? I don't understand why `eval` is necessary and an array feels more appropriate than concatenating `PARAMS` variable (I don't think the intention was to be POSIX-compliant anyway with `(( "$#" ))`. Is it relatively foolproof? I don't necessarily want a to use a non-standard library that implements this, so perhaps this is a good balance between simplicity (easy to understand) and provides the necessary useful features.
Sometimes my positional arguments involve filenames so it can technically start with a `-` (dash)--I'm not sure if that should be handled even though I stick to standard filenames (like those without newlines, etc.).
P.S. I believe one can hack `getopts` to support long-style options but I'm not sure if the added complexity is worth it over the seemingly more straightforward manual-parsing for long-style options like above.
https://redd.it/1kwez5l
@r_bash
Medium
Bash: Argument Parsing
One parser to rule them all
line 20: : no: integer expression expected
this happend when i enter "no"
this is my code, iam just trying to learn bash
https://preview.redd.it/io6jrw1kqc3f1.png?width=1033&format=png&auto=webp&s=05a622c6d70b1a88e7fe47ce3204fe58fb17a74f
[https://redd.it/1kwrugw
@r_bash
this happend when i enter "no"
this is my code, iam just trying to learn bash
https://preview.redd.it/io6jrw1kqc3f1.png?width=1033&format=png&auto=webp&s=05a622c6d70b1a88e7fe47ce3204fe58fb17a74f
[https://redd.it/1kwrugw
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community