Dispatcher does nothing on my machine?
I am using this commonly known script which isn't working for me at all. As in, no output and no changes in WiFi status:
​
#!/bin/bash
enabledisablewifi ()
{
result=$(nmcli dev | grep "ethernet" | grep -w "connected")
if -n "$result" ; then
nmcli radio wifi off
# echo "off"
else
nmcli radio wifi on
# echo "on"
fi
}
if "$2" = "up" ; then
enabledisablewifi
fi
if "$2" = "down" ; then
enabledisablewifi
fi
This is my output of "nmcli dev | grep "ethernet" | grep -w "connected"
enp52s0f3u1u3u4 ethernet connected My Ethernet
What am I doing wrong? :o
https://redd.it/1414kpb
@r_bash
Shell Scripting Tutorial
https://www.shellscript.sh/
https://redd.it/140hz7l
@r_bash
Idempotent mutation of PATH-like env variables
It always bothered me that every example of altering colon-separated values in an environment variable such as PATH
or LD_LIBRARY_PATH
(usually by prepending a new value) wouldn't bother to check if it was already in there and delete it if so, leading to garbage entries and violating idempotency (in other words, re-running the same command WOULD NOT result in the same value, it would duplicate the entry). So I present to you, prepend_path
:
# function to prepend paths in an idempotent way
prependpath() {
local dir="${1%/}" # discard trailing slash
local var="${2:-PATH}"
if [ -z "$dir" ]; then
echo "Usage: prependpath <pathtoprepend> name_of_path_var" >&2
return 2 # incorrect usage return code, may be an informal standard
fi
local newvalue=${!var}
[ $newvalue =~ ^$dir: ] && return # quit if value already starts with $dir
newvalue=${newvalue%:$dir} # remove $dir from end of path
newvalue=${newvalue//:$dir:/:} # remove $dir from middle of path
# prepend the new entry
export ${var}="$dir:$newvalue"
}
Usage examples:
prependpath $HOME/.linuxbrew/lib LDLIBRARYPATH
prependpath $HOME/.nix-profile/bin
Note that of course the order matters; the last one to be prepended that matches, triggers first, since it's put earlier in the PATHlike. Also, due to the use of some Bash-only features (I believe) such as the ${!var}
construct, it's only being posted to /r/bash =)
EDIT: code modified per /u/rustyflavor 's recommendations, which were good. thanks!!
https://redd.it/13zmp3w
@r_bash
Curious Bash: Get Notified When It's Done
https://blog.carlolobrano.com/posts/2023-06-02-curious-bash-get-notified-when-done/
https://redd.it/13zj9ly
@r_bash
woman - Preview list for man documents
https://gist.github.com/thingsiplay/f71383569c10da17f772b9967f5a5767
https://redd.it/13z41ji
@r_bash
How do I open a dir/filename with cat command?
For simplicity: I have a directory that contains two things: a setup script file, and another directory containing a text file with VS Code extensions, one per line. The paths to the two files would be:~/Downloads/scripts/setupscript
~/Downloads/scripts/VSCode/extensions.txt
I have this line in the setup script from this superuser topic:
cat VSCode/extensions.txt | xargs -n 1 code --install-extension
I get No such file or directory
errors when I run this line; despite trying a number of ways to get it to recognize the file like different path prefixes (/
, ./
, ../
) and even putting extensions.txt
in the same directory as setupscript
. Where am I going wrong?
https://redd.it/13ym85l
@r_bash
Maximize Productivity Of The Bash Shell
https://bluz71.github.io/2023/06/02/maximize-productivity-of-the-bash-shell.html
https://redd.it/13y4pg6
@r_bash
? - The only cheat sheet you need
https://gist.github.com/thingsiplay/69aada6a57f829d9580d7b54f8a207a0
https://redd.it/13xz1kc
@r_bash
Ksh etc. in 2023?
What do you guys think about still using a shell like the C shell or the Ksh shell? Are they still worth using?
https://redd.it/13xjds0
@r_bash
Is Recursion Stateful or Stateless?
Is recursion a stateful or stateless process?
On one hand, all previous iterations affect the next ones.
On the other hand, the function has no idea that it has ever been called before.
https://redd.it/13x4sbu
@r_bash
How to compress FileB with respect to, but not compressing, FileA?
Lets say I have FileA and FileB. They are nearly identical files. I am looking to compress the redundant data in FileB with respect to the original data in FileA, then go on to embed the compressed FileB within a metadata field of FileA for export. Eventually would need a process to reverse this as well.
I am not looking for any code but if this is possible and hopefully a point in the right direction. Thanks!
https://redd.it/13wwxtq
@r_bash
Sshto fix
Hi, I've just fixed some dumb error in sshto it didn't work if \~/.ssh/config file was missing O_o
Fixed that, enjoy)
https://redd.it/13wqfjs
@r_bash
Question about "ls" error messages, when/why are they suppressed if redirecting the output?
Some background for context only: I am creating a simple bash script that will check for stale file handles (most likely Samba mounts that became invalid because the remote system was rebooted, or similar), that I will run from /etc/crontab
. The script will then umount
/mount
to fix it, and this is not the part that I have a problem with.
​
The problem is that I wanted to find stale file handles by running ls -1
and looking for an error message such as ls: cannot access 'BAD_MOUNTPOINT': Stale file handle
. However, when I try to redirect the output to a mktemp
file or pipe it to grep
or similar, this error message does not seem to be displayed. Neither on stdout
or stderr
. It seems to me that ls
prints different things if it detects that a console (or not) will receive stdout
.
​
In this case, my workaround could be to list all files in the directory, pipe the output into a while IFS= read -r
loop and use stat
on each filename, which still works from a script. But I'd like to know why the ls
error output is suppressed. Any ideas?
(It's a bit annoying have a solution that works at the bash command line, but does not work in a script.)
https://redd.it/13wg9ol
@r_bash
Looking up for some projects ideas in BASH
I don't know where to look but I am stuck finding some good projects for Bash Scripting, if you have any suggestions then help.
https://redd.it/13vw3oh
@r_bash
these lines causing errors but I swear they weren't causing error before and I didn't change anything
i=0
while read l
do
varr=$(printf "$l" | awk --field-separator="|" "{ print NF }" )
"$varr" -eq 2 || "$varr" -eq 4 || i=$((i+2))
done < file
the error is this
[: Illegal number:
https://redd.it/140q88d
@r_bash
How to recursively rename photographs/videos to their respective folder name
To preface, I'm very new to bash. I have several thousand photographs and videos that I imported from Photos (macOS) and they were stored in folders based on their date. I'm not on Fedora and using gThumb and I cannot view all of my photographs/videos at once since there are so many sub-folders. I'd like to have them all in one folder, but still organized. So, as the title states, I'd like help writing a script that could recursively scan a directory (including one tier of sub-folders) and rename each photograph/video to the respective directory. Even better if it could remove any alphabetical letters.
Here's an example of a directory: Christmas Eve, December 24, 2018
Here's an example of what I'd like the files to be named: 12-24-2018 (1), 12-24-2018 (2), etc.
This way all of my photographs/videos could be stored in one folder.
Here's something I had tried:#!/bin/bash
for i in ~/Pictures/*/*.png;
do $parentFolder = dirname $i;
mv $i $parentFolder.png;
echo "Renamed $i to $parentFolder.png";
done
It obviously doesn't work, but I'd appreciate any help in fixing my errors.
https://redd.it/13zuyrj
@r_bash
Run a script into a new "less" istance then go back to the normal shell when the script has finished
Scenario: I want run a script into a terminal window, but to keep this window "clean" (ie I want to display only START and FINISHED) I want to display all the outputs into a clean space (like into the "less" command or even by opening it in "xterm"), then when the script has finisced I want to come back to the terminal window, automatically, so without having to press a key (like Q in "less"). All I want to see on that window is START and FINISCED! Nothing more. How should I do? I'm going mad!
https://redd.it/13zo2g6
@r_bash
What is this command?
I have a script that should run only when certain directory exists. It begins like that:
-d /home/path/to/directory &&
I found that example somewhere and it works, but I don't understand what these brackets really do. Is it correct way?
https://redd.it/13z8dfl
@r_bash
Script to simply read value give a not found error ?
Hi
I have a quite simple script and somehow i can't figure how to fix it.. It give me a not found all the time. If some do see the point...
nano /sbin/tempcpunotif.sh#!/bin/bash
while true; do
val=$(sensors | awk '/temp1/ {print $2}')
max="+75.0"
if [[ "$val" > "$max" ]]; then
systemctl suspend
fi
sleep 10
clear
sensors
done
exit 0
​
Or i try with a simpler one, but not sure as i told me the temp is not found..:
​#!/bin/sh
# Threshold for when to send alert
threshold=75000
​#sensors | grep -e "Package id 0" | while read line; do
cat /sys/devices/platform/coretemp.0/hwmon/hwmon1/temp1_input | while read line; do
temp=$(echo $line | awk -F "+" '{ print $2 }' | awk -F "." '{ print $1 }');
if (( temp > $threshold )); then sh /sbin/tempnotif.sh
fi;
done
​
Thanks in advance
https://redd.it/13yswnh
@r_bash
I don't understand how this lines with arrays works
Hello guys, we talked about bash arrays in our shell scripting course and the professor gave us this demonstration of a cool use of bash arrays but I am not able to understand why this works.
declare -A SELECTOR
declare -A SOMEDATA
declare -A OTHERDATA
SELECTORsome='SOMEDATA$KEY'
SELECTORother='OTHERDATA$KEY'
SOMEDATAfirstkey=somefirstvalue
SOMEDATAsecondkey=somesecondvalue
OTHERDATAfirstkey=otherfirstvalue
OTHERDATAsecondkey=othersecondvalue
KEY=firstkey
DATASET=some
echo ${!SELECTOR$DATASET}
#somefirstvalue
As I know, from bash manual:
>It is possible to obtain the keys (indices) of an array as well as the values. ${!name[@\]} and ${!name[*\]} expand to the indices assigned in array variable name. The treatment when in double quotes is similar to the expansion of the special parameters ‘@’ and ‘*’ within double quotes.
How this syntax of getting the assigned keys of an array let you create this dynamic dataset selection? I am not understanding the step-by-step expansions and operations performed by the shell. Also, I would like to know if any known shell scripts have used this approach to see a more consistent-real use.
Thanks.
https://redd.it/13yabi7
@r_bash
Installer script for CMake, Ninja, and Meson
I thought I would share my custom installer script for the latest GitHub versions of CMake, Ninja, and Meson.
It uses GitHub's API to grab the latest tag version of each repo and will install the static binaries to /usr/local/bin
bash <(curl -sSL https://build-tools.optimizethis.net)
This is my GitHub repo in case anyone wants to check it out before using: GitHub Script Repo
I hope someone finds this useful. (I know apt works but it doesn't install the latest versions usually).
And please let me know if something is wrong so I can make changes. =)
https://redd.it/13xy52n
@r_bash
Adding the value of an array to a variable
Im just learning bash so this question mighta bit stupid. What im trying to do, is to add the values of every colum of an array, that contain 100 letters at maximum, to an Variable and give out the sum. For this i have created the following script:#!/bin/bash
read save[1000]
i=0
sum=0
while (($i < 1000)); do
sum=$(($sum + ${save[$i]}))
((i++))
done
echo $sum
When executing i get the following error message:
line 5: 0 + : syntax error: operand expected (error token is "+ ")
How can i fix this?
https://redd.it/13xry3j
@r_bash
How to use scale in bc (for division) within a bash script and set it as a variable?
Hi, I am modifying a brightness volume bash script for my i3wm setup. The original script requires xbacklight which doesnt work on my system, so I need to tweak it a little. Anyway, this part of the script:
function show_brightness_notif {
brightness=${get_brightness}
# some more codes below for dunstify
}
The idea is that I need to divide this brightness by the max brightness, so I can get a percentage. I found out that you can do float arithmetic using bc, so:
function show_brightness_notif {
brightness=${get_brightness}
bc -l <<< $brightness/$max_brightness
}
This `max_brightness` is set outside the function as global, it is a fixed number. If I do this, calling the function from the command line will indeed show the decimal result. Problem is: it has a lot of decimal places. A quick search shows that you can limit decimal place using scale: [https://askubuntu.com/questions/217570/bc-set-number-of-digits-after-decimal-point](https://askubuntu.com/questions/217570/bc-set-number-of-digits-after-decimal-point)
But where do I write this `scale` variable? More specifically, how do I put everything (the division using bc, the scale) into 1 variable? Ideally, I would use dunst to output this variable.
https://redd.it/13xip20
@r_bash
Is this regex correct for what I'm trying to do?
So, first-off, I will admit, I know little about regex patterns. I'm trying to get a script to identify a \[music\] track filename with a track number, and only if the track number is a single digit, add a leading zero. I'm gonna get some cringes from the audience here, but please be gentle; I'm still very much a beginner, this is how the code for that looks at the moment, and spoiler alert, though no surprise to some, it doesn't work:
[if..then block begins]
elif [[ $filename =~ ^[0-9]+\ .+\.mp3$ ]]; then
local track_number=$(echo "$filename" | cut -d' ' -f1)
local title=$(echo "$filename" | cut -d' ' -f2-)
# Add leading zero if track number is a single character
if [[ ${#track_number} -eq 1 ]]; then
track_number="0$track_number"
fi
local new_filename="${track_number} ${title}"
if [[ "$filename" != "$new_filename" ]]; then
mv "$mp3_file" "$sub_dir/$new_filename"
log "Renamed: $filename --> $new_filename"
((files_renamed++))
else
log "No changes needed for: $filename"
fi
[if..then block continues]
I have plenty of tracks that are named like "1 Kryptonite.mp3" which I want renamed to "01 Kryptonite.mp3". I have close to 10,000 tracks in my library, so I'm not doing this by hand for the first 9 tracks of 677 albums.
Where am I going wrong, style aside? (I'm literally just trying to get this to work before I make it pretty)
And yes, everything is correctly declared and everything; this is the only part of the script I'm having issue with; the rest of the renaming conditions work fine.
https://redd.it/13wviwz
@r_bash
I made a simple script for splitting a physical monitor into virtual ones
https://redd.it/13wvk4a
@r_bash
declaring array using a variable
Given that I can declare an array like this and it creates a three element array perfectly ...
$ declare -a myarray=( 0=apple 1=pear 2=banana )
$ echo ${myarray1}
pear
...then why does this not behave in exactly the same way?
$ arraystring="0=apple 1=pear 2=banana"
$ declare -a myarray=( $arraystring )
$ echo ${myarray1}
1=pear
It still creates a three element array, but includes the key "1=" as part of the element contents. Why is this? I'm sure it has something to do with quoting but can't work it out. Quoting all the elements or quoting $arraystring doesn't seem to make a difference here.
https://redd.it/13wspgg
@r_bash
Problem with * in bash
Hello everyone,
I currently having a problem where the "*" is not replaced by anything in my bash file.
To add context, I'm trying to organize a game collection where I put every game that starts with a "t" in a "t" folder.
To avoid repeating the same two line in my she'll again and again, I wrote a bash script to do it for me.
I give it an argument (the letter "t" for example) and it create a folder and move every file beginning with t in it.
I wrote :
#!/bin/bash
mkdir $1
mv ${1}*.a26 $1/
But when I try to execute it, the mv command fail saying that it's impossible to evaluate 't*.a26' because there's no file or folder with this name.
(Just to be clear, I have several files beginning with t).
I can see that the problem comes because of the "*" that is not replaced with anything but I searched and didn't find a solution, neither by myself neither by researching.
So if someone can help me, I will be very thankful
https://redd.it/13wn10e
@r_bash
how to make graphical lines in a tui script?
​
https://preview.redd.it/rbwtz17ad23b1.png?width=81&format=png&auto=webp&v=enabled&s=178e21ff6f99409f03953b86634d2d329c2319be
I'm trying to make a tui program and I want straight lines like these, (for example ncmpcpp and bottom have them) But I have no idea how to make them using shell script. Are they just underscores or are they actually a line? and how are they positioned?
https://redd.it/13w06cc
@r_bash
my-bash-jazz
https://github.com/susonwaiba/my-bash-jazz
https://redd.it/13vufl9
@r_bash