Documentation for Bash?
Hi there! I was looking for Bash documentation, so my question is: is there any official documentation about this? If not, what’s the best docu site you recommend?
https://redd.it/1niobmh
@r_bash
Hi there! I was looking for Bash documentation, so my question is: is there any official documentation about this? If not, what’s the best docu site you recommend?
https://redd.it/1niobmh
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
How to do this process to all the videos in a directory?
I want to embed a thumbnail into mkv file. The command is something like this:
ffmpeg -i input.mkv -attach image.jpg -metadata:s:t:0 mimetype=image/jpeg -c copy output.mkv
How can I do this to all the video files in the folder? The name each video, and thumbnail is the same, except the extension(.mkv and .jpg)
https://redd.it/1njhwim
@r_bash
I want to embed a thumbnail into mkv file. The command is something like this:
ffmpeg -i input.mkv -attach image.jpg -metadata:s:t:0 mimetype=image/jpeg -c copy output.mkv
How can I do this to all the video files in the folder? The name each video, and thumbnail is the same, except the extension(.mkv and .jpg)
https://redd.it/1njhwim
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
How to solve this issue
so i am writing a noscript where i have like n files and everyfile just contain an array of same length so i want that the noscript iterate in the folder which contain that files ( a seprate folder) and read every file in loop 1 and in nested loop 2 i am reading and iterating the array i want to update some variables like var a i want that arr[0\] always do a=a+arr[0\] so that the a will be total sum of all the arr[0\].
For better understanding i want that the file contain server usage ( 0 45 55 569 677 1200) assume 10 server with diff value but same pattern i want the variable to be sum of all usage than i want to find do that it can be use in autoscaling.
current noscript so far
\#!/bin/bash
set -x
data="/home/ubuntu/exp/data"
cd "${data}"
count=1
avg=(0 0 0 0 0 0)
cpu_usr=0
cpu_sys=0
idle=0
ramused=0
ramavi=0
ramtot=0
file=(*.txt)
for i in "${file[@\]}"; do
echo "${i}"
mapfile -t numbers < "$i"
for j in "${numbers[@\]}"; do
val="${numbers[$j\]}"
clean=$(echo " $j " | tr -d '[:space:\]')
case $j in
*usr*) cpu_usr="clean" ;;
*sys*) cpu_sys="clean" ;;
*idle*) idle="clean" ;;
*ramus*) ramused="clean" ;;
*ramavi*) ramavi="clean" ;;
*ramtot*) ramtot="clean" ;;
esac
echo "$cpu_usr $cpu_sys $idle $ramused $ramavi $ramtot"
done
echo "$cpu_usr $cpu_sys $idle $ramused $ramavi $ramtot"
(( count++ ))
done
so i am stuck at iteration of array in a file
https://redd.it/1nji0zy
@r_bash
so i am writing a noscript where i have like n files and everyfile just contain an array of same length so i want that the noscript iterate in the folder which contain that files ( a seprate folder) and read every file in loop 1 and in nested loop 2 i am reading and iterating the array i want to update some variables like var a i want that arr[0\] always do a=a+arr[0\] so that the a will be total sum of all the arr[0\].
For better understanding i want that the file contain server usage ( 0 45 55 569 677 1200) assume 10 server with diff value but same pattern i want the variable to be sum of all usage than i want to find do that it can be use in autoscaling.
current noscript so far
\#!/bin/bash
set -x
data="/home/ubuntu/exp/data"
cd "${data}"
count=1
avg=(0 0 0 0 0 0)
cpu_usr=0
cpu_sys=0
idle=0
ramused=0
ramavi=0
ramtot=0
file=(*.txt)
for i in "${file[@\]}"; do
echo "${i}"
mapfile -t numbers < "$i"
for j in "${numbers[@\]}"; do
val="${numbers[$j\]}"
clean=$(echo " $j " | tr -d '[:space:\]')
case $j in
*usr*) cpu_usr="clean" ;;
*sys*) cpu_sys="clean" ;;
*idle*) idle="clean" ;;
*ramus*) ramused="clean" ;;
*ramavi*) ramavi="clean" ;;
*ramtot*) ramtot="clean" ;;
esac
echo "$cpu_usr $cpu_sys $idle $ramused $ramavi $ramtot"
done
echo "$cpu_usr $cpu_sys $idle $ramused $ramavi $ramtot"
(( count++ ))
done
so i am stuck at iteration of array in a file
https://redd.it/1nji0zy
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
Using ffmpeg to subnoscript your media; an example
https://ivo.palli.nl/2025/09/18/subnoscripts-using-ffmpeg/
https://redd.it/1njzwj5
@r_bash
https://ivo.palli.nl/2025/09/18/subnoscripts-using-ffmpeg/
https://redd.it/1njzwj5
@r_bash
Conway's Life Game... implemented in bash
My Gmail account shares a 15 gigabyte pool that can also be accessed via drive.google.com. I gave up fighting Github, and uploaded "life.tgz" to Google Drive. Instructions for download...
- point your web browser at https://drive.google.com/file/d/1QvJXQpM8PAXAhU6FjSkAHPacMhHWgM7n/view?usp=drivelink
- click on the "Download" icon, 3rd from the right at the top, to dowmload
- copy or move downloaded life.tgz to where ever you please (except /dev/shm)
- extract with the command "tar xzf life.tgz"
- this should create a directory named "life"
- "cd life" and read the "readme.txt" file
- if you have "$HOME/bin" in your path, it is strongly recommended to run "./setup". This noscript will create a "$HOME/bin/ttylife" symlink, enabling you to launch the game as "ttylife seedfile", without requiring the path to ttylife.
- ttylife will run in GUI terminals (e.g. xterm) and in true text consoles
- after launching ttylife, do NOT resize GUI term windows, or resize fonts in GUI windows or text consoles. If you want a maximized term window, do it before launching the game.
- if you have an older/slower machine, it may take a second or two to update after you tap the "n" key
https://redd.it/1nk4vqe
@r_bash
My Gmail account shares a 15 gigabyte pool that can also be accessed via drive.google.com. I gave up fighting Github, and uploaded "life.tgz" to Google Drive. Instructions for download...
- point your web browser at https://drive.google.com/file/d/1QvJXQpM8PAXAhU6FjSkAHPacMhHWgM7n/view?usp=drivelink
- click on the "Download" icon, 3rd from the right at the top, to dowmload
- copy or move downloaded life.tgz to where ever you please (except /dev/shm)
- extract with the command "tar xzf life.tgz"
- this should create a directory named "life"
- "cd life" and read the "readme.txt" file
- if you have "$HOME/bin" in your path, it is strongly recommended to run "./setup". This noscript will create a "$HOME/bin/ttylife" symlink, enabling you to launch the game as "ttylife seedfile", without requiring the path to ttylife.
- ttylife will run in GUI terminals (e.g. xterm) and in true text consoles
- after launching ttylife, do NOT resize GUI term windows, or resize fonts in GUI windows or text consoles. If you want a maximized term window, do it before launching the game.
- if you have an older/slower machine, it may take a second or two to update after you tap the "n" key
https://redd.it/1nk4vqe
@r_bash
epub-merge: A bash noscript to merge/split EPUB files
Just released
📚 Features:
- Merge multiple EPUBs into single volumes with organized TOC
- Split merged files back to originals (only epub-merge created files)
- Smart volume labeling for multiple languages (Korean, Japanese, Chinese, European languages)
- Minimal dependencies - just zip/unzip and basic shell tools
- Works on macOS and Linux
Perfect for organizing light novel series, manga volumes, or book collections! The tool automatically detects language and applies cultural-appropriate volume labels (제 1권, 第1卷, Volume 1, etc.)
GitHub: https://github.com/9beach/epub-merge
# Quick install
Would love feedback from fellow ebook enthusiasts!
https://redd.it/1nk5n4u
@r_bash
Just released
epub-merge - a simple bash noscript that handles EPUB merging and splitting right from your terminal!📚 Features:
- Merge multiple EPUBs into single volumes with organized TOC
- Split merged files back to originals (only epub-merge created files)
- Smart volume labeling for multiple languages (Korean, Japanese, Chinese, European languages)
- Minimal dependencies - just zip/unzip and basic shell tools
- Works on macOS and Linux
Perfect for organizing light novel series, manga volumes, or book collections! The tool automatically detects language and applies cultural-appropriate volume labels (제 1권, 第1卷, Volume 1, etc.)
GitHub: https://github.com/9beach/epub-merge
# Quick install
sudo curl -L https://raw.githubusercontent.com/9beach/epub-merge/main/epub-merge -o /usr/local/bin/epub-merge
sudo chmod a+rx /usr/local/bin/epub-merge
Would love feedback from fellow ebook enthusiasts!
https://redd.it/1nk5n4u
@r_bash
GitHub
GitHub - 9beach/epub-merge: Merge multiple ePUBs into one volume, or split volumes produced by epub-merge
Merge multiple ePUBs into one volume, or split volumes produced by epub-merge - 9beach/epub-merge
Utility dumpall — Bash CLI to dump files into Markdown for AI/code reviews
Wrote a Bash-based CLI called `dumpall` that aggregates files into Markdown.
Great for AI prompts, debugging, or just archiving.
Features:
\- Clean Markdown output
\- Smart exclusions (--exclude)
\- Copy-to-clipboard (--clip)
\- Colorized output
Works cross-platform (Linux/macOS, WSL, Git Bash on Windows).
Repo 👉 https://github.com/ThisIsntMyId/dumpall
https://redd.it/1nkknyx
@r_bash
Wrote a Bash-based CLI called `dumpall` that aggregates files into Markdown.
Great for AI prompts, debugging, or just archiving.
Features:
\- Clean Markdown output
\- Smart exclusions (--exclude)
\- Copy-to-clipboard (--clip)
\- Colorized output
Works cross-platform (Linux/macOS, WSL, Git Bash on Windows).
Repo 👉 https://github.com/ThisIsntMyId/dumpall
https://redd.it/1nkknyx
@r_bash
GitHub
GitHub - ThisIsntMyId/dumpall: A CLI utility to aggregate file contents into Markdown format, perfect for AI context and code reviews
A CLI utility to aggregate file contents into Markdown format, perfect for AI context and code reviews - ThisIsntMyId/dumpall
BASH must haves?
Hello, I am somewhat new to Linux and BASH. Are there any apps, packages which are really nice to have? For example I would really appriciate some kind of autocomplete feature for typing commands. Any suggestions how to achieve this?
Thank you very much :)
https://redd.it/1nm816y
@r_bash
Hello, I am somewhat new to Linux and BASH. Are there any apps, packages which are really nice to have? For example I would really appriciate some kind of autocomplete feature for typing commands. Any suggestions how to achieve this?
Thank you very much :)
https://redd.it/1nm816y
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
Multiple files as stdin?
I have a C++ program that takes a .txt file, transforms it into a matrix, then takes another .txt file and transforms that into a matrix:
vector<vector<float>> A = convert();
Matrix worker(A);
vector<vector<float>> B = convert();
Matrix auxiliary(B);
convert():
vector<vector<float>> convert(){
vector<vector<float>> tokens;
int row = 0;
int col = 0;
string line;
string token;
while(getline(cin, line)){
if(line.empty()){
break;
}
tokens.push_back(vector<float> {});
while ((col = line.find(' ')) != std::string::npos) {
token = line.substr(0, col);
tokens[row].push_back(stof(token));
line.erase(0, col + 1);
}
token = line.substr(0);
tokens[row].push_back(stof(token));
line.erase(0, token.length());
col = 0;
row++;
}
return tokens;
}
how would I pass two separate text files in to the program?
https://redd.it/1njmbr0
@r_bash
I have a C++ program that takes a .txt file, transforms it into a matrix, then takes another .txt file and transforms that into a matrix:
vector<vector<float>> A = convert();
Matrix worker(A);
vector<vector<float>> B = convert();
Matrix auxiliary(B);
convert():
vector<vector<float>> convert(){
vector<vector<float>> tokens;
int row = 0;
int col = 0;
string line;
string token;
while(getline(cin, line)){
if(line.empty()){
break;
}
tokens.push_back(vector<float> {});
while ((col = line.find(' ')) != std::string::npos) {
token = line.substr(0, col);
tokens[row].push_back(stof(token));
line.erase(0, col + 1);
}
token = line.substr(0);
tokens[row].push_back(stof(token));
line.erase(0, token.length());
col = 0;
row++;
}
return tokens;
}
how would I pass two separate text files in to the program?
https://redd.it/1njmbr0
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
Generate & preview Doxygen docs with one command on Linux 🚀
I got tired of running `doxygen` and then manually opening `index.html` every time, so I wrote a tiny Bash noscript to automate it.
👉 Run one command, and it:
* Generates your Doxygen HTML docs
* Finds `index.html`
* Opens it in your default browser automaticall
Script (GitHub Gist): [https://gist.github.com/artyom-fedosov/5e4f1385716450852a3e57189b804f1e](https://gist.github.com/artyom-fedosov/5e4f1385716450852a3e57189b804f1e)
No more typing `doxygen` then manually opening `index.html`. Works on Linux, perfect for C/C++ projects.
Open to any feedback or ideas to make it better!
https://redd.it/1nms4ej
@r_bash
I got tired of running `doxygen` and then manually opening `index.html` every time, so I wrote a tiny Bash noscript to automate it.
👉 Run one command, and it:
* Generates your Doxygen HTML docs
* Finds `index.html`
* Opens it in your default browser automaticall
Script (GitHub Gist): [https://gist.github.com/artyom-fedosov/5e4f1385716450852a3e57189b804f1e](https://gist.github.com/artyom-fedosov/5e4f1385716450852a3e57189b804f1e)
No more typing `doxygen` then manually opening `index.html`. Works on Linux, perfect for C/C++ projects.
Open to any feedback or ideas to make it better!
https://redd.it/1nms4ej
@r_bash
Gist
Bash noscript to generate Doxygen HTML docs and open them in the default browser
Bash noscript to generate Doxygen HTML docs and open them in the default browser - README.md
glrl - Green light/Red light, monitor boolean bash expressions at a glance
Sharing this hoping it can make life easier for someone out there 😊 I found myself spamming different commands to check status of things in Linux while testing some code. So I wrote this little shell noscript to simplify life. There's probably something something similar out there, but I couldn't find anything simple enough with some (very) quick googling.
https://github.com/Wesztman/glrl
I have on my todo to make it possible to input config file path.
https://redd.it/1nn1zum
@r_bash
Sharing this hoping it can make life easier for someone out there 😊 I found myself spamming different commands to check status of things in Linux while testing some code. So I wrote this little shell noscript to simplify life. There's probably something something similar out there, but I couldn't find anything simple enough with some (very) quick googling.
https://github.com/Wesztman/glrl
I have on my todo to make it possible to input config file path.
https://redd.it/1nn1zum
@r_bash
GitHub
GitHub - Wesztman/glrl: A simple status monitor written in bash with a dynamic configuration
A simple status monitor written in bash with a dynamic configuration - GitHub - Wesztman/glrl: A simple status monitor written in bash with a dynamic configuration
The source command closes the terminal
I have a noscript
and an alias in the
Now, when i write
The problem arises, when i don't specify any parameters (virtual environment name). Then the
https://redd.it/1no0pid
@r_bash
I have a noscript
venvs.sh:#!/bin/bash
BASE_PATH=/home/ether/.venvs
SOURCE_PATH=bin/activate
if [ -z "$1" ]; then
echo "Usage:"
echo "venvs.sh ENV_NAME"
exit 0
fi
if [ ! -d "$BASE_PATH" ]; then
mkdir $BASE_PATH
if [ ! -d "$BASE_PATH" ]; then
echo "BASE_PATH '$BASE_PATH' does not exist."
exit 0
fi
fi
if [ ! -d "$BASE_PATH/$1" ]; then
python3 -m venv $BASE_PATH/$1
fi
FULL_PATH=$BASE_PATH/$1/$SOURCE_PATH
if [ ! -f "$FULL_PATH" ]; then
echo "Environment '$FULL_PATH' does not exist."
exit 0
fi
source $FULL_PATH
and an alias in the
.bash_aliases:alias venv='source /home/ether/bin/venvs.sh'
Now, when i write
venv testenv, the virtual environment named testenv is created and/or opened. It works like a charm.The problem arises, when i don't specify any parameters (virtual environment name). Then the
source command closes the terminal. How can i avoid this? I don't want to close the terminal.https://redd.it/1no0pid
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
Possible breaking changes that would actually improve bash. What's your ideas?
I'll start:
Make it so that when i can use `echo -- ...` and echo doesn't print the -- and understand it as to stop reading its options. Instead i have to use printf.
Make it so that i can provide a delimiter to echo other than a space, possibly a string instead of single character. Therefore i can do `echo --delim $'\\n' *`, because sometimes it's usefull to have the files on separate lines. Instead i currently have to do `ls` or `echo * | tr ' ' $'\\n'` in these situations.
Scoped functions/commands definitions? Making callbacks would be better if the callback command doesn't still exists when its containing command returns.
Possilibity of having bash lists inside other lists. Recursive data structures would enable many things (such as lisp).
https://redd.it/1np2dy0
@r_bash
I'll start:
Make it so that when i can use `echo -- ...` and echo doesn't print the -- and understand it as to stop reading its options. Instead i have to use printf.
Make it so that i can provide a delimiter to echo other than a space, possibly a string instead of single character. Therefore i can do `echo --delim $'\\n' *`, because sometimes it's usefull to have the files on separate lines. Instead i currently have to do `ls` or `echo * | tr ' ' $'\\n'` in these situations.
Scoped functions/commands definitions? Making callbacks would be better if the callback command doesn't still exists when its containing command returns.
Possilibity of having bash lists inside other lists. Recursive data structures would enable many things (such as lisp).
https://redd.it/1np2dy0
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
How do I do this with bash?
I have multiple videos and images in one folder. The goal is to use ffmpeg to add thumbnails to the videos.
the command to attach a thumbnail to a single video is
ffmpeg -i input.mkv -attach image.jpg -metadata:s:t:0 mimetype=image/jpeg -c copy output.mkv
The videos named as such
00001 - vidname.mkv
00002- vidname.mkv
00100 - vidname.mkv
01000 - vidname.mkv
and etc
as you can see, I have added number prefixes with a padding of zeros to the video names. The corresponding images are named in a similar manner .
00001.jpg
00002.jpg
00100.jpg
I want to attach the images to the videos based on the prefixes.
00001.jpg is to be attached to 00001 - vidname.mkv, and so on
https://redd.it/1npapqb
@r_bash
I have multiple videos and images in one folder. The goal is to use ffmpeg to add thumbnails to the videos.
the command to attach a thumbnail to a single video is
ffmpeg -i input.mkv -attach image.jpg -metadata:s:t:0 mimetype=image/jpeg -c copy output.mkv
The videos named as such
00001 - vidname.mkv
00002- vidname.mkv
00100 - vidname.mkv
01000 - vidname.mkv
and etc
as you can see, I have added number prefixes with a padding of zeros to the video names. The corresponding images are named in a similar manner .
00001.jpg
00002.jpg
00100.jpg
I want to attach the images to the videos based on the prefixes.
00001.jpg is to be attached to 00001 - vidname.mkv, and so on
https://redd.it/1npapqb
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
Checksums and deduplicating on QNAP / Linux
https://ivo.palli.nl/2025/09/24/checksums-and-deduplicating-on-qnap-linux/
https://redd.it/1npliug
@r_bash
https://ivo.palli.nl/2025/09/24/checksums-and-deduplicating-on-qnap-linux/
https://redd.it/1npliug
@r_bash
Few functions and aliased I use on my ~/.bashrc
Sometimes it's good to post something you wanted to read in a specific /r, so I'm doing it.
Down below there are a couple of functions and aliases that I have on my \~/.bashrc that I find extremely useful and handy. Let me know if those can be improved somehow.
Hope it'll help at least one person!
cd(){
if [[ $1 =~ ^-[0-9]+$ ]]; then
local n=${1#-}
local path=""
for(( i=0;i<n;i++ )); do
path+="../"
done
builtin cd "$path"
else
builtin cd "$@"
fi
}
rename(){
local n="$*"
PROMPT_COMMAND="echo -en '\033]0;${n}\007'"
}
export PATH="$HOME/.local/bin:$PATH"
alias execute="chmod +x"
alias editsh="vim ~/.bashrc"
alias sourcesh="source ~/.bashrc"
alias uu="sudo apt update && sudo apt upgrade -y"
alias desk="cd ~/Desktop"
alias down="cd ~/Downloads"
alias udb="sudo updatedb"
alias release="lsb_release -a"
https://redd.it/1nq77o6
@r_bash
Sometimes it's good to post something you wanted to read in a specific /r, so I'm doing it.
Down below there are a couple of functions and aliases that I have on my \~/.bashrc that I find extremely useful and handy. Let me know if those can be improved somehow.
Hope it'll help at least one person!
cd(){
if [[ $1 =~ ^-[0-9]+$ ]]; then
local n=${1#-}
local path=""
for(( i=0;i<n;i++ )); do
path+="../"
done
builtin cd "$path"
else
builtin cd "$@"
fi
}
rename(){
local n="$*"
PROMPT_COMMAND="echo -en '\033]0;${n}\007'"
}
export PATH="$HOME/.local/bin:$PATH"
alias execute="chmod +x"
alias editsh="vim ~/.bashrc"
alias sourcesh="source ~/.bashrc"
alias uu="sudo apt update && sudo apt upgrade -y"
alias desk="cd ~/Desktop"
alias down="cd ~/Downloads"
alias udb="sudo updatedb"
alias release="lsb_release -a"
https://redd.it/1nq77o6
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
What are ways to setup an isolated environment for testing shell noscripts?
I want to check that my shell noscripts won't fail if some non-standard commands are missing (e.g.
What are your thoughts?
https://redd.it/1nqhwpb
@r_bash
I want to check that my shell noscripts won't fail if some non-standard commands are missing (e.g.
qemu-system-*). To solve this problem with the least overhead only tools like schroot, docker or lxd come to mind. I think that potentially I could change in some way environment variables like PATH to emulate missing commands. However, I also want to prevent harming my FS while testing noscripts (protect myself from accidental sudo rm -rf --no-preserve-root /).What are your thoughts?
https://redd.it/1nqhwpb
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
LLaMA en macOS
* Estoy trabajando en un conjunto de noscripts Bash para manejar modelos LLaMA en macOS. Aquí va un ejemplo de cómo valido dependencias con bash. ¿Alguien más ha intentado algo parecido?
* $MAIN\_BINARY" \\
* \-m "$MODELO\_PATH" \\
* \--ctx-size 31000 \\
* \--n-predict 500 \\
* \--color \\
* \--temp 1.2 \\
* \--threads 6 \\
* \--prompt "$(cat "$PROMPT\_SISTEMA") $(cat "$PROMPT\_FILE")" 2>&1 | grep -v 'llama\_' | tee >(tee -a "$LOG\_PATH") >> "$TEMP\_OUT"
https://redd.it/1nqxdhm
@r_bash
* Estoy trabajando en un conjunto de noscripts Bash para manejar modelos LLaMA en macOS. Aquí va un ejemplo de cómo valido dependencias con bash. ¿Alguien más ha intentado algo parecido?
* $MAIN\_BINARY" \\
* \-m "$MODELO\_PATH" \\
* \--ctx-size 31000 \\
* \--n-predict 500 \\
* \--color \\
* \--temp 1.2 \\
* \--threads 6 \\
* \--prompt "$(cat "$PROMPT\_SISTEMA") $(cat "$PROMPT\_FILE")" 2>&1 | grep -v 'llama\_' | tee >(tee -a "$LOG\_PATH") >> "$TEMP\_OUT"
https://redd.it/1nqxdhm
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
xargs for functions
I love the power of `xargs`. But it doesn't work with Bash functions. Here is `fargs`, which works with functions.
# Usage: source ~/bin/lib.sh
# This is a libary to be sourced by noscripts, such as ~/.bashrc:
# fargs - xargs for functions
# No space in xargs options. Bad: -n 2. Good: -n2 or --max-args=2
# All bash functions and local env vars will be accessible.
# otherwise, works just like xargs.
fargs() {
# Find the index of the first non-option argument, which should be the command
local cmd_start_index=1
for arg in "$@"; do
if [[ "$arg" != -* ]]; then
break
fi
((cmd_start_index++))
done
# Extract xargs options and the command
local opts=("${@:1:$((cmd_start_index - 1))}")
local cmd=("${@:$cmd_start_index}")
if [[ ${#cmd[@]} -eq 0 ]]; then cmd=("echo"); fi
# xargs builds command strings by passing stdin items as arguments to `echo`.
# The resulting strings (e.g., "my_func arg1") are then executed by `eval`.
# This allows xargs to call shell functions, which are not exported to subshells.
eval "$(xargs "${opts[@]}" bash -c 'printf "%q " "$@"; echo' -- "${cmd[@]}")"
}
https://redd.it/1nqij6u
@r_bash
I love the power of `xargs`. But it doesn't work with Bash functions. Here is `fargs`, which works with functions.
# Usage: source ~/bin/lib.sh
# This is a libary to be sourced by noscripts, such as ~/.bashrc:
# fargs - xargs for functions
# No space in xargs options. Bad: -n 2. Good: -n2 or --max-args=2
# All bash functions and local env vars will be accessible.
# otherwise, works just like xargs.
fargs() {
# Find the index of the first non-option argument, which should be the command
local cmd_start_index=1
for arg in "$@"; do
if [[ "$arg" != -* ]]; then
break
fi
((cmd_start_index++))
done
# Extract xargs options and the command
local opts=("${@:1:$((cmd_start_index - 1))}")
local cmd=("${@:$cmd_start_index}")
if [[ ${#cmd[@]} -eq 0 ]]; then cmd=("echo"); fi
# xargs builds command strings by passing stdin items as arguments to `echo`.
# The resulting strings (e.g., "my_func arg1") are then executed by `eval`.
# This allows xargs to call shell functions, which are not exported to subshells.
eval "$(xargs "${opts[@]}" bash -c 'printf "%q " "$@"; echo' -- "${cmd[@]}")"
}
https://redd.it/1nqij6u
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
Expect driving me crazy! Timeout or Loop or Nada
I try to read the firmware version of a device from a spawned ssh connection. So far so good. I have a block that basically puts "We are in" just as a debug print to see, wether the login works. Next block:
# Detecting firmware version
set deviceInfoRequested "no"
send "\r"
expect {
-re "#" {
if {"\$deviceInfoRequested" eq "no"} {
set deviceInfoRequested "yes"
send "show device\r"
after 500
expcontinue
}
}
-re {Firmware Version: ([0-9]+)\.([0-9]+)} {
set major \$expectout(1,string)
set minor \$expectout(2,string)
puts "Detected Firmware version: \$major.\$minor"
# Compare numerically
if { (\$major > 4) || (\$major == 4 && \$minor > 2) } {
puts ">>> using newer Syntax for gateway"
set raritanVersion "new"
} else {
set raritanVersion "classic"
puts ">>> using old Syntax for gateway"
}
flush stdout
}
timeout {
puts "Timeout waiting for firmware version"
set raritanVersion "unknown"
exit 1
}
} # Detecting firmware version
set deviceInfoRequested "no"
send "\r"
expect {
-re "#" {
if {"\$deviceInfoRequested" eq "no"} {
set deviceInfoRequested "yes"
send "show device\r"
after 500
expcontinue
}
}
-re {Firmware Version: (0-9+)\.(0-9+)} {
set major \$expectout(1,string)
set minor \$expectout(2,string)
puts "Detected Firmware version: \$major.\$minor"
# Compare numerically
if { (\$major > 4) || (\$major == 4 && \$minor > 2) } {
puts ">>> using newer Syntax for gateway"
set raritanVersion "new"
} else {
set raritanVersion "classic"
puts ">>> using old Syntax for gateway"
}
flush stdout
}
timeout {
puts "Timeout waiting for firmware version"
set raritanVersion "unknown"
exit 1
}
}
Without the if deviceInfoRequested it loops forever as each new prompt starts with # logically. If I put the # at the end after the Firmware Version detection block (which has no line exp_continue), it first sends show device, than successfully prints "Detected Firmware version: 4.4" and than waits for 5 seconds before the noscript exits... Why, if exp_continue is not used, does it not escape the expect {} block? Of course there are further blocks that follow... But it just times out. I tried
first expect block > Prints "We are in" directly (before printing the rest that SSH still receives)
puts "HI"
after 5000
next expect block
The ovserved behavior is not what you might expect: After "We are in" NOTHING is printed for 5 seconds straight. Only than the rest of the login prompt is even printed an donly than we see the HI. Is it just me or is expect a horrible mess? How Shall I implement the logic to detect the firmware here? Direct SSH commands I would prefer, but the device does not support it. I need to rely on expect. I have written a screen handler that does the same that expect does... But it is sooo complicated and hard to debug that I wanted to try something simpler and yet lightweight.
By the way: The "flush stdout" was just a test to see if it makes a difference in behavior/order. Nada. Not at all.
Please tell me you understand what is going on here and why it either just times out, or loops forever or sleeps before printing to stdout although I defined it the other way around. I am not sure what is going on
I try to read the firmware version of a device from a spawned ssh connection. So far so good. I have a block that basically puts "We are in" just as a debug print to see, wether the login works. Next block:
# Detecting firmware version
set deviceInfoRequested "no"
send "\r"
expect {
-re "#" {
if {"\$deviceInfoRequested" eq "no"} {
set deviceInfoRequested "yes"
send "show device\r"
after 500
expcontinue
}
}
-re {Firmware Version: ([0-9]+)\.([0-9]+)} {
set major \$expectout(1,string)
set minor \$expectout(2,string)
puts "Detected Firmware version: \$major.\$minor"
# Compare numerically
if { (\$major > 4) || (\$major == 4 && \$minor > 2) } {
puts ">>> using newer Syntax for gateway"
set raritanVersion "new"
} else {
set raritanVersion "classic"
puts ">>> using old Syntax for gateway"
}
flush stdout
}
timeout {
puts "Timeout waiting for firmware version"
set raritanVersion "unknown"
exit 1
}
} # Detecting firmware version
set deviceInfoRequested "no"
send "\r"
expect {
-re "#" {
if {"\$deviceInfoRequested" eq "no"} {
set deviceInfoRequested "yes"
send "show device\r"
after 500
expcontinue
}
}
-re {Firmware Version: (0-9+)\.(0-9+)} {
set major \$expectout(1,string)
set minor \$expectout(2,string)
puts "Detected Firmware version: \$major.\$minor"
# Compare numerically
if { (\$major > 4) || (\$major == 4 && \$minor > 2) } {
puts ">>> using newer Syntax for gateway"
set raritanVersion "new"
} else {
set raritanVersion "classic"
puts ">>> using old Syntax for gateway"
}
flush stdout
}
timeout {
puts "Timeout waiting for firmware version"
set raritanVersion "unknown"
exit 1
}
}
Without the if deviceInfoRequested it loops forever as each new prompt starts with # logically. If I put the # at the end after the Firmware Version detection block (which has no line exp_continue), it first sends show device, than successfully prints "Detected Firmware version: 4.4" and than waits for 5 seconds before the noscript exits... Why, if exp_continue is not used, does it not escape the expect {} block? Of course there are further blocks that follow... But it just times out. I tried
send "show device\r" before the expect block, but than it just does not detect it. Also strange: My first expect block waits for either "Welcome" or "#" to detect: Yes I am logged in. This is where it puts "We are in". If I write something like:first expect block > Prints "We are in" directly (before printing the rest that SSH still receives)
puts "HI"
after 5000
next expect block
The ovserved behavior is not what you might expect: After "We are in" NOTHING is printed for 5 seconds straight. Only than the rest of the login prompt is even printed an donly than we see the HI. Is it just me or is expect a horrible mess? How Shall I implement the logic to detect the firmware here? Direct SSH commands I would prefer, but the device does not support it. I need to rely on expect. I have written a screen handler that does the same that expect does... But it is sooo complicated and hard to debug that I wanted to try something simpler and yet lightweight.
By the way: The "flush stdout" was just a test to see if it makes a difference in behavior/order. Nada. Not at all.
Please tell me you understand what is going on here and why it either just times out, or loops forever or sleeps before printing to stdout although I defined it the other way around. I am not sure what is going on