r_bash – Telegram
What level does using mindepth or maxdepth for a find command start at?

I am writing a bash noscript and a little unsure about the min/max depth option for the find command.

I have this find command and want to add maxdepth and mindepth to it

find /local/applogs/archive/ -type d -mtime +366 -exec echo {} \;


And this is the full depth of the directory, what number would I use for the depth options?

/local/applogs/archive/host/comp/2021/01/

The point of the find will eventually be to find any empty directories that are over a year old and remove them using rmdir which should make sure they are empty. Except it should only remove old, empty year and month (2021 and 01) directories.

Would I start the depth count from / or from the directory I am beginning my search (archive)?

​

https://redd.it/16cgem5
@r_bash
A working alternative to someprogram & disown & exit

I have trawled around looking for a solution for what seems should be fairly trivial.
It's worth noting that I am using wayland (**insert rant about not being able to generalize over compositors, this is the one thing making me think of switching back to X).


I have tried all manner of things including fetching the id of the current window, launching the program, disowning, & then closing the window with the id, but after running disown the call to exit or whatever after is never ran leaving the term open.


Any suggestions at all?
Still a bit of a bash novice, any reading materials also appreciated. Thanks.

https://redd.it/16cm8d8
@r_bash
writing a single line of a process output to a file

Hello, i want to write a single line of a process to a file , basically i want a command to write a single line to a file when there is a new notification. i tried different things without success:

dbus-monitor "member='Notify',interface='org.freedesktop.Notifications'" | grep-e "member=Notify" | while read line;do
echo "new line" >> ca.txt
done

​

dbus-monitor "member='Notify',interface='org.freedesktop.Notifications'" | grep-e "member=Notify" | while read line;do
tee -a ca.txt
done

​

dbus-monitor "member='Notify',interface='org.freedesktop.Notifications'" | tee company.txt >(grep "member=Notify" >> ad.txt)

but it seems the grep output isn't redirected to tee or echo . when i add -m1 flag to grep it writes the single line to the file but after 3 times the command exits but i want it to keep running . does anyone knows what im doing wrong?

https://redd.it/16cpa3v
@r_bash
Exit command failure

The following is a noscript to read the news:

```
#!/bin/bash

day=$(date +%d | cut -c 2 | awk '{print $1 - 1}')
month=$(date +%m | cut -c 2)
year=$(date +%Y)

xdg-open https://www.somenews.com-$day-$month-$year/ > /dev/null 2>&1

exit
```

i'd like the terminal to close after i execute the noscript but it doesn't.


but if i make an `alias` in my bashrc:

`alias news_item="yesterday_news.sh && exit"`


then it works as expected and closes the terminal.

What's causing it?



----

terminal=alacritty
web_browser=vivaldi

https://redd.it/16d1gd4
@r_bash
Why does the prompt combine with the last line of stdout?

Sometimes this happens

user@DESKTOP:~$ printf "$(cat file1.txt)"
dog
cow
catuser@DESKTOP:~$

The last line of the stdout cat would combine with the prompt user@DESKTOP:~$?

What would cause the prompt not to be on a new and separate line? I assume sometimes the terminal glitches out and I have to accept it (and restart it) but I suspect there is a reasoning behind this.

https://redd.it/16d1k41
@r_bash
Script doesn't work in cron

This noscript in /home/media works and does what it needs to. It doesn't work when setup as cron.

I tried cd /home/media before the loop but couldn't find mkv files.

How do I make it work ?

OS is ubuntu server.

#!/bin/bash

for F in **/*.mkv; do
###
some code
###
done
exit 0

https://redd.it/16d4dsq
@r_bash
why test makes this noscript to fail?

Please consider these two noscripts:

run.sh:

#!/bin/bash
set -euo pipefail
. "$(dirname $(realpath $BASHSOURCE))"/init-sudo-noscript.sh

`init-sudo-noscript.sh`

[ ${
#BASHSOURCE@} -eq 1 ]\
&& echo "must be sourced by another noscript."\
&& exit 10

$EUID -ne 0 \
&& echo "must be executed as root."\
&& exit 20

This is correct and it is what I expect to happen:

$ ./run.sh
must be executed as root.
$ echo $?
20

But this I can't understand:

$ sudo ./run.sh
$ echo $?
1

I know the problem is [ $EUID -ne 0 ] because the noscript works when I remove it.

I also understand set -e makes the noscript to exit on any error.

What I don't understand is why the first guard condition ([ ${#BASH_SOURCE[@]} -eq 1 ]) doesn't exit with 1 when it fails but the second does.

Does anybody understand what is happening here?

https://redd.it/16d7hg0
@r_bash
Can this be done with the level of single line simplicity I'm trying to accomplish?

I just started learning bash and I'm trying to make a noscript resolve with the smallest amount of code possible. The problem is as follows:

>Create a new noscript called calculate-average.sh. The noscript should accept exactly 3 command-line arguments and calculate the average. The result should not round the value to the nearest integer.

The issue I'm having is not how to solve the problem with multiple lines but with one. This is where I've gotten so far:

echo $(((($1+$2+$3)/3) | bc -l))

So far the addition and the division work fine but when it comes to printing the result as a float (for cases with uneven numbers), that last bit of code keeps getting ignored for some reason. Is there a way to do it or do I forcefully need to resort to 2 lines of code?

https://redd.it/16d8r76
@r_bash
Help on find file with max number in filename and replace

I’m playing with bash on Mac but got some challenges which I haven’t found the way to solve. Please give me some suggestions. Thanks!

I have list of following file in folder:
abcen.srt
abcen1.srt
abcen2.srt

abc
enn.srt

- How can I find the file with max “n”?
- If I want to replace “abc
en.srt” with “abcenn.srt” (if it exists), how can I achieve this?

https://redd.it/16de4p3
@r_bash
Export variables from shell noscript to expect noscript

Hi i have problem with export variables from
ports..sh
I want to automate installing something and i need ports from inside of the container. If i use only for reading (echo commands) its work well, but when i try to catch thats ports in expect.sh i throw error.

How to do that correctly?


expect.sh
Expect works well without variables

#!/usr/bin/expect


spawn bash -c {....command....}

source ports.sh

set timeout 600

expect {
...expect noscript...
"$port1\r"
"$port2\r"
"$port3\r
}
}

exit




ports.sh

#!/bin/bash

netstat_output=$(netstat -tuln)

port1=""
port2=""
port3=""

while IFS= read -r line; do

ip_address=$(echo "$line" | awk '{print $4}' | awk
-F: '{print $2}' | awk -F. '{print $NF}')


if [[ $ip_address =~ ^[0-9]+$ ]]; then

if [[ $ip_address =~ ^8 ]]; then
port1="$port1 $ip_address"
elif [[ $ip_address =~ ^9 ]]; then
port2="$port2 $ip_address"
elif [[ $ip_address =~ ^10 ]]; then
port3="$port3 $ip_address"
fi
fi
done <<< "$netstat_output"

# echo "Ports 8..."
export port1="${port1# }"

# echo "Ports 9..."
export port2="${port2# }"

# echo "Ports 10..."
export port3="${port3# }"


Error


/ # ./autoUpdate.sh
spawn bash -c [command]
can't read "(netstat -tuln)": no such variable
while executing
"netstat_output=$(netstat -tuln)"
(file "ports.sh" line 3)
invoked from within
"source ports.sh"
(file "./autoUpdate.sh" line 6)
/ # source ports.sh
bin/sh: ports.sh: line 24: syntax error:
unexpected redirection
/ #

https://redd.it/16ecvd1
@r_bash
Integer express expected

So in my .sh file I have a command called

"(curl ${HOSTIP}:9200/cluster/health | jq .numberofdatanodes)"

this is checking elastic's health. So I always get error unknown command integer expression expected and unknown command '.number\
of_data_nodes' even though this command curl ${HOST_IP}:9200/_cluster_health does return an object containing {"number_of_data_nodes":1} there's also other stuff returned too but lets keep it to this for now. I'm not sure why it can't recognize it

https://redd.it/16eefyg
@r_bash
run service as root but get current user info?

I don't know if I'm supposed to be posting in Gnome or Wayland subreddit, but I'm a noob, so please help me out if you can.

I'm trying to run a systemd service that gets idle time and assigns it to a variable:

getidletime=/usr/bin/dbus-send --print-reply --dest=org.gnome.Mutter.IdleMonitor /org/gnome/Mutter/IdleMonitor/Core org.gnome.Mutter.IdleMonitor.GetIdletime

However, idle time is user specific, so it always fails. I've tried sudo -u $USER and sudo -u <specific user> both inside and outside the backticks. Any ideas?

https://redd.it/16etxvv
@r_bash
Converting from string to json in a .sh file

If I have a variable called

res='{number_of_data_nodes:1}'

how can I convert this to a JSON object so it prints like a json object and not a string

https://redd.it/16f88zx
@r_bash
Why does this attempt to read/write to arrays not work?

!#/bin/bash

declare -a testarray
count=0
testvariable0=dog ; testvariable1=cat

while $count -lt 2
do
testarray$count+="$testvariable$count"
((count++))
done

echo ${testarray0}
echo -e
echo ${testarray1}

I'm going to write a function that i'm going to reuse a lot. The function will be pointed at an arbitary position in an array, so I thought that I could replace the specifying number with the contents of a variable.

To test this, I made this short looping noscript.

Expected output:

dog

cat

actual output:

0

1

What gives?

https://redd.it/16g4e2z
@r_bash
What is your best tool/command to look into log files?

Probably `less` with something like:

bat --style=plain --color=always {FILE_NAME} | less -R

but still wanted to know more if there are any better tools/commands/tricks to do that.

The tools I can think of now:

* `less` \- can provide a very powerful [advanced search](https://man7.org/linux/man-pages/man1/less.1.html#COMMANDS) e.g. using `&` pattern to filter the lines
* `bat` \- colored with the ability to search in the window (probably similar to `less` if uses it as the default pager)
* `cat` and `grep` - I will have to repeat the command more than once and takes more time
* `vim -R` (or `view`) - in read-only mode

https://redd.it/16ga0t9
@r_bash
I noscript I use to find files broke mysteriously and started adding newlines where spaces in directory name exist.

I have a noscript that searches through a large filesystem, matches file names against search criteria, makes a list of them, hashes them all and eliminates duplicates, and then copies all the files to a directory.

It's breaking now for some odd reason and it seems to be messing up where directory names have spaces, treating the space as a newline. I figure I'm missing a flag or a basic concept, any ideas? Here's the beginning of it:

#!/bin/bash

declare -a FILENAMES
declare -A HASHES

read -p "What are you searching for? " varname

echo Searching for "$varname"

if -d "/mnt/me/output/$varname" ; then
echo "Directory already exists, quitting."
exit
fi

printf "\n"

FILENAMES=( $(find /mnt/archive /mnt/dad -type f -size +512k -iname """$varname""") )

MATCHES=${#FILENAMES@}

echo "Found $MATCHES matches:"

for i in "${FILENAMES@}"
do
echo "$i"
done

I omitted the rest of the code since it is irrelevant. Is find failing me?

https://redd.it/16gje76
@r_bash
Quoting strings more resiliently

I wish there were some simple syntax, where we could easily quote strings, and ' and " would not throw it off. It's way too common to use ' and " when typing sentences, accidentally messing up the quoted parameter.

The alternatives, like heredocs, going back and assigning a variable, etc., are not convenient for fast interactive use as you're just quickly trying to get things done. Some syntax like ${this is a string} would be great (I know that one won't work). Possibly one where the delimiting char were selectable, like in perl q/str/, where you set the first char, like q|str| -- this also handles paired char types, e.g. q{str} and q(str). You can even do q\\str\\. (q for single-quote functionality, qq for double-quote functionality) (And, of course, the same provision is available for matches with m// and regex replacements, s/foo/bar/ => s#foo#bar# => s{foo}{bar})


&#x200B;

https://redd.it/16gl9qz
@r_bash
Question on subshell

Hi everyone ,

I'm currently reading a book "Linux Command Line and Shell Scripting Bible" and when I was studying about the concept on how to extract the value from the output and send it to a variable (which I completely understood) , Author calls this method "Command Substitution" .

After that there was this "Warning" section . In which the highlighted part I wasn't able to really understand .

I did refer this stackoverflow question over here > https://serverfault.com/questions/723391/subshell-is-not-created-if-run-commands-without-a-path

but I wasn't able to get it still .

If someone can please take out there time to help me understand this concept I would highly appreciate it thanks !

https://preview.redd.it/63sogx5i4unb1.png?width=985&format=png&auto=webp&s=298687b726f205cd7a9467a430bcdf3fa8e0aea8

https://redd.it/16gsxgm
@r_bash
What's this X$1 Thing?

I've run across "X$1" recently and I'm at a loss. Anyone have any ideas what it could be? If you could illustrate your explanation with a simple example, that would be fantastic, as I usually get things better this way.

https://redd.it/16gull2
@r_bash